作者:百色金融新闻网日期:
返回目录:金融新闻
最新资讯《SpringBoot 整合 Apache ActiveMQ-activemq》主要内容是activemq,SpringBoot整合ApacheActiveMQ1.pom.xml添加依赖<dependency>。,现在请大家看具体新闻资讯。
SpringBoot 整合 Apache ActiveMQ
1. pom.xml 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2. 修改application.yml
spring:
activemq:
broker-url: tcp://192.168.44.129:61616
user: admin
password: admin
3. 创建消息生产者Producer
package cn.tyrone.springboot.integrate.activemq;
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
/**
* 消息生产者
*
*/
@Component
public class Producer {
/*
* Jms消息模板
*/
@Autowired private JmsMessagingTemplate jmsMessagingTemplate;
/*
* 队列
*/
@Autowired private Queue queue;
/*
* 发送消息
*/
public void send(String msg){
this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
}
}
4. 创建消息消费者Consumer
package cn.tyrone.springboot.integrate.activemq;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
@JmsListener(destination = "sample.queue")
public void receiveMessge(String text){
System.out.println("发送的消息:\\t" + text);
}
}
5. 创建SpringBoot启动类
package cn.tyrone.springboot.integrate.activemq;
import javax.jms.Queue;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
@SpringBootApplication
@EnableJms
public class Application implements CommandLineRunner {
/*
* 声明一个消息队列
*/
@Bean
public Queue queue() {
return new ActiveMQQueue("sample.queue");
}
/*
* 注入消息生产者
*/
@Autowired private Producer Producer;
@Override
public void run(String... args) throws Exception {
Producer.send("Hello! SpringBoot integrate Apache ActiveMQ!!!");
System.out.println("发送消息结束!!!");
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
运行启动类后,查看控制台日志: