1 activemq安装,我这里利用docker 安装
安装完成后 默认密码为admin/admin
image.png
界面样子还是挺老的
2 在springboot项目中引入依赖,进行配置
引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
yml配置
spring:
activemq:
broker-url: tcp://10.0.59.161:61616 #你activeMQ的ip和tcp端口号(默认就是61616)
user: admin #activeMq账号
password: admin #activeMq密码
jms:
pub-sub-domain: false # false代表队列,true代表主题
queue: queue01 # 自定义命名队列
创建一个配置类
@Component
@EnableJms // 开启JMS适配
public class ConfigBean {
@Value("${queue}")
private String myQueue; // 注入配置文件中的queue
@Bean
public ActiveMQQueue queue() {
return new ActiveMQQueue(myQueue);
}
@Bean
public Topic topic() {
return new ActiveMQTopic("my-topic");
}
}
3 创建好后,开始测试activemq 的两种模式,创建一个测试类
/**
* Queue为点对点模式,即有一个消息,才能有一个消费,多个消费者不会重复对应一个消息。
*
* Topic为一对多形式,当订阅者订阅后,发布者发布消息所有订阅者都会接受到消息。
* @Param
* @return
**/
@SpringBootTest
class ConfigBeanTest {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private ActiveMQQueue queue;
// pub-sub-domain: false # false代表队列,true代表主题
// 队列模式
@Test
void queue() {
jmsMessagingTemplate.convertAndSend(queue, "这是一条消息");
}
@JmsListener(destination = "${queue}") // 注解监听
public void receive(TextMessage textMessage) throws Exception {
System.out.println("消费者收到消息:" + textMessage.getText());
}
@JmsListener(destination = "${queue}") // 注解监听
public void receive1(TextMessage textMessage) throws Exception {
System.out.println("消费者收到消息1:" + textMessage.getText());
}
// 主题模式
// pub-sub-domain: true
@Autowired
private Topic topic;
/**
* 发送主题消息
*/
@Test
public void sendTopic() {
this.jmsMessagingTemplate.convertAndSend(this.topic, "主题模式");
}
@JmsListener(destination = "my-topic")
public void receiveTopic(String message){
System.out.println("TopicConsumer接收的消息是:"+message);
}
@JmsListener(destination = "my-topic")
public void receiveTopic1(String message){
System.out.println("TopicConsumer1接收的消息是:"+message);
}
}
分别运行两个测试方法即可看到效果
运行两种模式的时候,记得更改相应的 yml中的 配置(更改ture false)
queue() 方法运行后,只有一个队列能收到消息
sendTopic()方法运行后, 两个主题模式的队列都能收到相同的消息
具体代码
https://gitee.com/flgitee/test