这里使用SpringBoot整合ActiveMQ,同时测试queue和topic两种消息模式。
项目结构:
pom导入jar包:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-activemq -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
</dependencies>
application.yml文件:
server:
port: 80
spring:
activemq:
broker-url: tcp://192.168.232.135:61616
user: admin
password: admin
#默认是queue消息,即为false,当为true时,是topic模式的消息
jms:
pub-sub-domain: false
首先进行queue模式的消息测试:
生产者类SpringBootActiveMQProducer.class:
@RestController
@RequestMapping("/producer")
public class SpringBootActiveMQProducer {
@Autowired
private JmsTemplate jmsTemplate;
@RequestMapping("/send")
public void send(){
jmsTemplate.send("test-springboot-activemq", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage();
textMessage.setText("test");
System.out.println("生产消息成功");
return textMessage;
}
});
}
/*
此方式也可以生产消息
@RequestMapping("/send")
public void send(){
jmsTemplate.convertAndSend("test-springboot-activemq","test");
System.out.println("生产消息成功");
}
*/
}
消费者类SpringBootActiveMQCustomer.class:
@Component
public class SpringBootActiveMQCustomer {
@JmsListener(destination = "test-springboot-activemq")
public void receiveOne(Message message) throws JMSException {
TextMessage textMessage = (TextMessage) message;
System.out.println("One接收到消息:" + textMessage.getText());
}
@JmsListener(destination = "test-springboot-activemq")
public void receiveTwo(Message message) throws JMSException {
TextMessage textMessage = (TextMessage) message;
System.out.println("Two接收到消息:" + textMessage.getText());
}
}
SpringBoot启动类SpringBootActiveMQApplication.class:
@SpringBootApplication
public class SpringBootActiveMQApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootActiveMQApplication.class, args);
}
}
启动后我们查看ActiveMQ管理界面,发现此时queue模式内有两个消费者已经建立:
接着进行消息的生成,在浏览器输入:127.0.0.1/producer/send即可生产消息,我们直接生产4条消息,然后查看ActiveMQ管理界面和控制台,4条消息皆被消费掉,然后控制台可以看出,一条消息只被一个消费者消费,因为建立了两个消费者,因此是轮流进行消息的消费的,具体的消费机制算法,会在之后的博客中再进行讲解:
接着我们来进行topic模式的消息测试:
只需要修改配置文件:
server:
port: 80
spring:
activemq:
broker-url: tcp://192.168.232.135:61616
user: admin
password: admin
#默认是queue消息,即为false,当为true时,是topic模式的消息
jms:
pub-sub-domain: true
然后启动我们的项目,到ActiveMQ管理界面查看,topic界面会发现有两个消费者
生产两条消息,然后查看管理界面和控制台,发现有两条消息,但是消费了4条,因为是topic模式,每条消息会被建立的每隔消费者消费,即2*2=4,控制台也能发现每个消息都被两个消费者消费了:
至此,SpringBoot整合ActiveMQ以及进行两种消息模式的测试结束。