1. 創建一個springboot項目,添加依賴
<!--ActiveMq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
<!--消息隊列連接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.15.0</version>
</dependency>
2、application.yml文件的配置
server:
port: 8080
spring:
activemq:
broker-url: tcp://127.0.0.1:61616
user: admin
password: admin
close-timeout: 15s # 在考慮結束之前等待的時間
in-memory: true # 默認代理URL是否應該在內存中。如果指定了顯式代理,則忽略此值。
non-blocking-redelivery: false # 是否在回滾回滾消息之前停止消息傳遞。這意味着當啓用此命令時,消息順序不會被保留。
send-timeout: 0 # 等待消息發送響應的時間。設置爲0等待永遠。
queue-name: active.queue
topic-name: active.topic.name.model
# packages:
# trust-all: true #不配置此項,會報錯
pool:
enabled: true
max-connections: 10 #連接池最大連接數
idle-timeout: 30000 #空閒的連接過期時間,默認爲30秒
# jms:
# pub-sub-domain: true #默認情況下activemq提供的是queue模式,若要使用topic模式需要配置下面配置
# 是否信任所有包
#spring.activemq.packages.trust-all=
# 要信任的特定包的逗號分隔列表(當不信任所有包時)
#spring.activemq.packages.trusted=
# 當連接請求和池滿時是否阻塞。設置false會拋“JMSException異常”。
#spring.activemq.pool.block-if-full=true
# 如果池仍然滿,則在拋出異常前阻塞時間。
#spring.activemq.pool.block-if-full-timeout=-1ms
# 是否在啓動時創建連接。可以在啓動時用於加熱池。
#spring.activemq.pool.create-connection-on-startup=true
# 是否用Pooledconnectionfactory代替普通的ConnectionFactory。
#spring.activemq.pool.enabled=false
# 連接過期超時。
#spring.activemq.pool.expiry-timeout=0ms
# 連接空閒超時
#spring.activemq.pool.idle-timeout=30s
# 連接池最大連接數
#spring.activemq.pool.max-connections=1
# 每個連接的有效會話的最大數目。
#spring.activemq.pool.maximum-active-session-per-connection=500
# 當有"JMSException"時嘗試重新連接
#spring.activemq.pool.reconnect-on-exception=true
# 在空閒連接清除線程之間運行的時間。當爲負數時,沒有空閒連接驅逐線程運行。
#spring.activemq.pool.time-between-expiration-check=-1ms
# 是否只使用一個MessageProducer
#spring.activemq.pool.use-anonymous-producers=true
3、啓動類增加 @EnableJms 註解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.annotation.EnableJms;
@SpringBootApplication
@EnableJms //啓動消息隊列
public class SpringbootActivemqApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootActivemqApplication.class, args);
}
}
4、初始化和配置 ActiveMQ 的連接
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
@Configuration
publicclass BeanConfig
{
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
@Value("${spring.activemq.user}")
private String username;
@Value("${spring.activemq.topic-name}")
private String password;
@Value("${spring.activemq.queue-name}")
private String queueName;
@Value("${spring.activemq.topic-name}")
private String topicName;
@Bean(name = "queue")
public Queue queue() {
return new ActiveMQQueue(queueName);
}
@Bean(name = "topic")
public Topic topic() {
return new ActiveMQTopic(topicName);
}
@Bean
public ConnectionFactory connectionFactory(){
return new ActiveMQConnectionFactory(username, password, brokerUrl);
}
@Bean
public JmsMessagingTemplate jmsMessageTemplate(){
return new JmsMessagingTemplate(connectionFactory());
}
// 在Queue模式中,對消息的監聽需要對containerFactory進行配置
@Bean("queueListener")
public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(false);
return factory;
}
//在Topic模式中,對消息的監聽需要對containerFactory進行配置
@Bean("topicListener")
public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(true);
return factory;
}
}
5、生產者(queue 和 topic)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
@RestController
public class ProducerController
{
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Autowired
private Topic topic;
@PostMapping("/queue/test")
public String sendQueue(@RequestBody String str) {
this.sendMessage(this.queue, str);
return "success";
}
@PostMapping("/topic/test")
public String sendTopic(@RequestBody String str) {
this.sendMessage(this.topic, str);
return "success";
}
// 發送消息,destination是發送到的隊列,message是待發送的消息
private void sendMessage(Destination destination, final String message){
jmsMessagingTemplate.convertAndSend(destination, message);
}
}
6、Queue模式的消費者
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class QueueConsumerListener
{
//queue模式的消費者
@JmsListener(destination="${spring.activemq.queue-name}", containerFactory="queueListener")
public void readActiveQueue(String message) {
System.out.println("queue接受到:" + message);
}
}
7、topic模式的消費者
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class TopicConsumerListener
{
//topic模式的消費者
@JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
public void readActiveQueue(String message) {
System.out.println("topic接受到:" + message);
}
}
topic模式有普通訂閱和持久化訂閱
普通訂閱:在消費者啓動之前發送過來的消息,消費者啓動之後不會去消費;
持久化訂閱: 在消費者啓動之前發送過來的消息,消費者啓動之後會去消費;