spring boot 项目集成ActiveMQ
话不多说,直接上代码
1、导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
2、在application.yml 配置activeMQ链接
activemq:
enable: false #是否启动activeMQ配置
queue: false #启用activeMQ 队列模式
topic: false #启用ActiveMQ topic模式
queue-name: lcfc.websocket.queue # 队列名
topic-name: lcfc.websocket.topic # topic名
urls:
- tcp://127.0.0.1:61616
- tcp://127.0.0.1:61617
- tcp://127.0.0.1:61618
- tcp://127.0.0.1:61619
- tcp://127.0.0.1:61620
- tcp://127.0.0.1:61621
3、编写配置类
3.1 读取activeMQ配置
@ConditionalOnExpression("${activemq.enable:false}")
@ConfigurationProperties(prefix = "activemq")
public class ActiveMqConfig {
private List<String> urls;
private String queueName;
private String topicName;
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public List<String> getUrls() {
return urls;
}
public void setUrls(List<String> urls) {
this.urls = urls;
}
}
3.2 编写ActiveMQ queue配置类
@Slf4j
@ConditionalOnExpression("${activemq.enable:false} and ${activemq.queue:false}")
@Configuration
public class ActivemqQueueConfiguration {
@Bean
public ActiveMqConfig activeMqConfig(){
return new ActiveMqConfig();
}
@Bean
public Queue productActiveMQQueue(){
return new ActiveMQQueue(activeMqConfig().getQueueName());
}
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerQueue() {
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
String BROKER_URL = "failover:("+ StringUtils.join(activeMqConfig().getUrls(),",")+")";
log.info("BROKER_URL={}",BROKER_URL);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
factory.setTrustAllPackages(true);
bean.setConnectionFactory(factory);
return bean;
}
@Bean
public JmsMessagingTemplate jmsMessagingTemplate(){
String BROKER_URL = "failover:("+ StringUtils.join(activeMqConfig().getUrls(),",")+")";
return new JmsMessagingTemplate(new ActiveMQConnectionFactory(BROKER_URL));
}
}
3.3 编写ActiveMQ topic配置类
@Slf4j
@ConditionalOnExpression("${activemq.enable:false} and ${activemq.topic:false}")
@Configuration
public class ActivemqTopicConfiguration {
@Bean
public ActiveMqConfig activeMqConfig(){
return new ActiveMqConfig();
}
@Bean
public MessageProducer getMessageProducer() {
String BROKER_URL = "failover:("+ StringUtils.join(activeMqConfig().getUrls(),",")+")";
log.info("BROKER_URL={}",BROKER_URL);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
MessageProducer producer = null;
Connection connection = null;
try {
//2. 创建Connection
connection = factory.createConnection();
//3. 启动连接
connection.start();
//4. 创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5. 创建一个目标
Destination destination = session.createTopic(activeMqConfig().getTopicName());
producer= session.createProducer(destination);
} catch (JMSException e) {
log.error("获取activeMQ producer发生错误={}",e.getMessage());
if (connection!=null){
connection.close();
}
}finally {
return producer;
}
}
@Bean
public MessageConsumer messageConsumer() {
String BROKER_URL = "failover:("+ StringUtils.join(activeMqConfig().getUrls(),",")+")";
log.info("BROKER_URL={}",BROKER_URL);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
MessageConsumer consumer =null;
Connection connection = null;
//2. 创建Connection
try {
connection = factory.createConnection();
//3. 启动连接
connection.start();
//4. 创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5. 创建一个目标
Destination destination = session.createTopic(activeMqConfig().getTopicName());
consumer = session.createConsumer(destination);
} catch (JMSException e) {
e.printStackTrace();
if (connection!=null){
connection.close();
}
}finally {
return consumer;
}
}
}
3.4 编写 queue consumer
public interface LcfcMqHandler {
/**
* 消费者 接收到消息 执行的操作
* @param msg
*/
void doHandler(String msg);
}
@Slf4j
public class DefaultMqHandler implements LcfcMqHandler{
@Override
public void doHandler(String msg) {
log.info("接收到消息={}",msg);
}
}
@Slf4j
@Component
@AllArgsConstructor
@NoArgsConstructor
@ConditionalOnExpression("${activemq.enable:false} and ${activemq.queue:false}")
public class LcfcActiveMQConsumer {
private LcfcMqHandler handler;
@JmsListener(destination = "${activemq.queue-name}",containerFactory = "jmsListenerContainerQueue")
public void receiveQueue(String text) {
log.info("接受消息={}",text);
handler.doHandler(text);
}
}
3.5 编写 queue 、topic 的 product
// 定义product 发送接口
public interface ProductSendMessage {
void sendMessage(Object message)throws ActiveSendException;
}
// queue
@Component
@ConditionalOnExpression("${activemq.enable:false} and ${activemq.queue:false}")
public class LcfcActiveMQProducer implements ProductSendMessage {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue productActiveMQQueue;
@Override
public void sendMessage(Object message)throws ActiveSendException {
this.jmsMessagingTemplate.convertAndSend(this.productActiveMQQueue,message);
}
}
// topic
@Slf4j
@Component
@ConditionalOnExpression("${activemq.enable:false} and ${activemq.topic:false}")
public class LcfcActiveMQTopicProducer implements ProductSendMessage {
@Autowired
MessageProducer messageProducer;
@Override
public void sendMessage(Object message)throws ActiveSendException {
TextMessage msg = new ActiveMQTextMessage();
try {
msg.setText(message.toString());
} catch (JMSException e) {
log.error("activeMQ 消息:{}发生错误:{}",message,e.getMessage());
throw new ActiveSendException(e.getMessage());
}
}
}
3.6 topic consumer
/**
* 初始化 ActiveMQ topic 消费者
*/
@Slf4j
@Component
@ConditionalOnExpression("${activemq.enable:false} and ${activemq.topic:false}")
public class InitActiveConsumer implements ApplicationRunner {
@Autowired
MessageService messageService;
@Override
public void run(ApplicationArguments args) throws Exception {
initMessageConsumer();
}
@Autowired
MessageConsumer consumer;
private void initMessageConsumer() {
try {
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message instanceof TextMessage){
try {
log.info("msg={}", ((TextMessage) message).getText());
String msg = ((TextMessage) message).getText();
if (msg.contains(Constants.STRING_SPLIT)){
String[] msgs = msg.split(Constants.STRING_SPLIT);
if (msgs.length==3){
String from = msgs[0];
String to =msgs[1];
String sendMsg = msgs[2];
TextWebSocketFrame tws = new TextWebSocketFrame(sendMsg);
Boolean send = WebsocketUtils.sendToOne(to,tws);
if (send){
}
// TODO 去除重复
MessageEntity entity = MessageEntity.builder().message(sendMsg)
.from(from).to(to)
.createTime(new Date())
.delete(MessageConstants.deleteStatus.NO)
.read(MessageConstants.readStatus.NO).build();
messageService.addData(entity);
}
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
log.info("消费者启动成功");
} catch (JMSException e) {
e.printStackTrace();
}
}