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.然后运行发布者
在这里插入图片描述
发布者运行之后,发送消息,能立刻被订阅到。

发布了62 篇原创文章 · 获赞 29 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/csdn_20150804/article/details/104577571