引入maven 用到的jar包依赖,pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 继承父包 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.songzixian</groupId>
<artifactId>springboot-activemq</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- spring-boot的启动类的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- spring-boot的web启动的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-boot的启动类的测试jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- spring boot整合activemq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
</dependencies>
<!-- spring boot默认插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
编写applicaion.yml
文件
server:
post: 6666
spring:
activemq:
#ActiveMQ的地址
broker-url: tcp://192.168.78.138:61616
#ActiveMQ的用户名
user: admin
#ActiveMQ的密码
password: admin
jms:
#fasle=Queue(不写默认) true=Topic
pub-sub-domain: true
#自定义队列的名称
myTopic: boot-activemq-topic
编写消息生产者配置类
/**
* @author songzixian
* @create 2019-07-19 下午 8:44
* @description 队列消息生产者
*/
@Component
public class Topic_Produce {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Topic topic;
//消息生成者
@Scheduled(fixedDelay = 3000)//定时每间隔3秒投送
public void produceMsg(){
//发送主题消息
jmsMessagingTemplate.convertAndSend(topic,"----"+UUID.randomUUID().toString().substring(0,6));
System.out.println("生产者发送了一条消息");
}
}
/**
* @author songzixian
* @create 2019-07-19 下午 11:20
* @description
*/
@Component
public class Topic_Consumer {
@JmsListener(destination = "${myTopic}")
public void receive(TextMessage textMessage)throws Exception {
System.out.println("消费者接收到了消息"+textMessage.getText());
}
}
编写消息消费者配置类
/**
* @author songzixian
* @create 2019-07-19 下午 11:20
* @description
*/
@Component
public class Topic_Consumer {
@JmsListener(destination = "${myTopic}")
public void receive(TextMessage textMessage)throws Exception {
System.out.println("消费者接收到了消息"+textMessage.getText());
}
}
编写spring boot启动类
/**
* @author songzixian
* @create 2019-07-19 下午 8:53
* @description
*/
@SpringBootApplication
@EnableScheduling//开启定时投送
public class MainApp_Produce {
public static void main(String[] args) {
SpringApplication.run(MainApp_Produce.class,args);
}