springboot整合ActiveMQ Topic(笔记)

1.创建一个springboot项目pom.xm导入jar包

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

2.application.yml

server:
  port: 8081

spring:
  activemq:
    broker-url: tcp://192.168.200.128:61616
    user: admin
    password: admin
  jms:
    pub-sub-domain: true #false = Queue true=Topic 默认false

#自定义队列名称
myTopic: boot-activemq-topic

3.配置Ben

package com.example.activemq.config;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.jms.Topic;

@Component
public class ActiveMqConfig {

    @Value("${myTopic}")
    private String myTopic;
 
    @Bean
    public Topic topic(){
        return new ActiveMQTopic(myTopic);
    }

}


4. TopicProduce生产者

package com.example.activemq.topic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.jms.Topic;
import java.util.UUID;

@Component
@EnableJms
public class TopicProduce {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Topic topic;

    public void produceMsg(){
        jmsMessagingTemplate.convertAndSend(topic,"Topic主题消息:"+UUID.randomUUID().toString().substring(0,6));

    }
}

5.TopicConsumer消费着

package com.example.activemq.topic;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.TextMessage;

@Component
public class TopicConsumer {

    @JmsListener(destination = "${myTopic}")
    public void receive(TextMessage textMessage) throws Exception{
        System.out.println("*******Topic消费者接收到消息:"+textMessage.getText());
    }
}

6.测试类

package com.example.activemq;
import com.example.activemq.topic.TopicProduce;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ActivemqDemoApplicationTests {
    
    @Autowired
    private TopicProduce topicProduce;
    
    @Test
    void contextLoads() {
        topicProduce.produceMsg();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值