消息發(fā)送者
1、創(chuàng)建SpringBoot工程13-activemq-boot-sender作為 消息發(fā)送者
2、在pom.xml文件中添加相關依賴
這個依賴在創(chuàng)建Module的時候,如果勾選了集成ActiveMQ會自動生成
<!--SpringBoot集成ActiveMQ的起步依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
3、 在SpringBoot的核心配置文件application.properties中配置ActiveMQ的連接信息
#配置activemq的連接信息
spring.activemq.broker-url=tcp://192.168.235.128:61616
#目的地
spring.jms.template.default-destination=bootQueue
#默認是緩存了jms的session的,所以主程序發(fā)送完消息后,不會退出
# 改為false主程序才可以退出 從SpringBoot2.1.0以后新增的
spring.jms.cache.enabled=false
4、在com.bjpowernode.activemq.service包下創(chuàng)建一個MessageService類,并提供發(fā)送消息的方法(可以從12-activemq-spring-sender直接拷貝)
@Service
public class MessageService {
//這里的JmsTemplate是SpringBoot自動配置的
@Autowired
private JmsTemplate jmsTemplate;
public void sendMessage(){
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("Hello,Spring ActiveMQ");
}
});
}
}
5、在SpringBoot的主程序中編寫測試代碼,運行測試發(fā)送消息
@SpringBootApplication
public class Application {
public static void main(String[] args) {
//獲取Spring容器
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
//根據(jù)容器獲取bean對象
MessageService messageService = context.getBean("messageService", MessageService.class);
//調(diào)用bean對象的方法, 發(fā)送消息
messageService.sendMessage();
}
}
6、在ActiveMQ控制臺查看效果
1、 創(chuàng)建SpringBoot工程13-activemq-boot-receiver作為 消息接收者
2、在pom.xml文件中添加相關依賴
這個依賴在創(chuàng)建Module的時候,如果勾選了集成ActiveMQ會自動生成
<!--SpringBoot集成ActiveMQ的起步依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
3、在SpringBoot的核心配置文件application.properties中配置ActiveMQ的連接信息
#配置activemq的連接信息
spring.activemq.broker-url=tcp://192.168.235.128:61616
#目的地
spring.jms.template.default-destination=bootQueue
#默認是緩存了jms的session的,所以主程序發(fā)送完消息后,不會退出
# 改為false主程序才可以退出 從SpringBoot2.1.0以后新增的
spring.jms.cache.enabled=false
4、在com.bjpowernode.activemq.service包下創(chuàng)建一個MessageService類,并提供接收消息的方法(可以從12-activemq-spring-receiver直接拷貝)
@Service
public class MessageService {
//這里的JmsTemplate是SpringBoot自動配置的
@Autowired
private JmsTemplate jmsTemplate;
public void receiveMessage(){
Message message = jmsTemplate.receive();
if(message instanceof TextMessage){
try {
String text = ((TextMessage) message).getText();
System.out.println("SpringBoot接收到的消息為:" + text);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
5、在SpringBoot的主程序中編寫測試代碼,運行測試接收消息
SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
//根據(jù)容器獲取bean對象
MessageService messageService = context.getBean("messageService", MessageService.class);
//調(diào)用bean對象的方法, 接收消息
messageService.receiveMessage();
}
}
6、在ActiveMQ控制臺查看效果