ActiveMQ系列(三)springboot整合ActiveMQ实现消息的发布订阅

上篇文章《ActiveMQ系列(二)》中实现了消息队列模式,本文开始实现主题消息的发布和订阅。

maven依赖

新建springboot的过程不再赘述,这里在pom文件中直接以用maven依赖:

<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

yml配置

spring:
  activemq:
    broker-url: tcp://192.168.17.101:61616
    user: admin
    password: admin
  jms:
    pub-sub-domain: true #默认false = Queue   true = Topic
    
#自己定义的主题名称
mytopic: boot-activemq-topic

配置bean

@Component
@EnableJms
public class ActiveMqConfigBean {

    @Value("${mytopic}")
    private String myTopic;

    @Bean
    public Topic topic() {
        return new ActiveMQTopic(myTopic);
    }
}

生产者

@Component
public class TopicProduce {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic topic;

    @Scheduled(fixedDelay = 3000)//定时发布消息
    public void produceTopic() {
        jmsMessagingTemplate.convertAndSend(topic, "*****" + UUID.randomUUID().toString().substring(0, 6));
    }
}

消费者

消费者,应该新建一个单独的项目,类似生产者,这里不再赘述,然后编写消费者,

@Component
public class TopicConsumer {
    @JmsListener(destination = "${mytopic}")
    public void receive(TextMessage textMessage) throws JMSException {
        System.out.println("订阅者消费消息:" + textMessage.getText());
    }
}

单元测试

1.发布订阅模式,要先启动订阅者,启动后会发现有一个消费者:
在这里插入图片描述
2.然后运行发布者
在这里插入图片描述
发布者运行之后,发送消息,能立刻被订阅到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值