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
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();
}
}