springboot activemq stomp实现队列消息发送/消费

1.添加maven依赖

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
            <version>5.14.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-stomp</artifactId>
            <version>5.14.5</version>
        </dependency>
    </dependencies>

2.application.properties

#activemq
activemq.host=192.168.1.23
activemq.port=61613
activemq.user=admin
activemq.password=admin
spring.activemq.pool.enabled=true
spring.activemq.pool.max-connections=10
#默认情况下activemq提供的是queue模式,若要使用topic模式需要配置下面配置
spring.jms.pub-sub-domain=true

3.生产者 JmsProducer

package com.yangfeng.msservice.service;

import org.apache.activemq.transport.stomp.Stomp;
import org.apache.activemq.transport.stomp.StompConnection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.UUID;

/**
 * 消息生产者
 *
 * @author yangfeng
 * @date 2020-03-09
 */
@Component
public class JmsProducer {

    @Value("${activemq.user}")
    private String userName;

    @Value("${activemq.password}")
    private String password;

    @Value("${activemq.host}")
    private String host;

    @Value("${activemq.port}")
    private Integer port;


    public StompConnection connectionFactory() throws Exception {
        StompConnection conn = new StompConnection();
        conn.open(host, port);
        conn.connect(userName, password);
        return conn;
    }

    /**
     * 发送JMS消息
     *
     * @throws Exception exception
     */
    public void sendMessage(String queueName, String message)
            throws Exception {
        StompConnection stompConnection = connectionFactory();
        String tx = UUID.randomUUID().toString().replaceAll("-", "");
        HashMap<String, String> headers = new HashMap<>();
        headers.put(Stomp.Headers.Send.PERSISTENT, "true");
        stompConnection.begin(tx);
        stompConnection.send(queueName, message, tx, headers);
        stompConnection.commit(tx);
        stompConnection.disconnect();
    }

}

4.消费者JmsConsumer

import com.alibaba.fastjson.JSONException;
import com.yangfeng.msservice.service.JmsProducer;
import com.yangfeng.service.IAllocationResultService;
import org.apache.activemq.transport.stomp.StompConnection;
import org.apache.activemq.transport.stomp.StompFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.SocketTimeoutException;
import java.util.Map;

/**
 * 从消息队列中消费
 *
 * @author yangfeng
 * @date 2020-04-09
 */

@Component
public class JmsConsumer implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger LOG = LoggerFactory.getLogger(FlightAssignparkConsumer.class);

    @Resource
    private IResultService resultService;

    @Resource
    public JmsProducer jmsProducer;

    private static final String QUEUE_FLIGHT_ASSIGNPARK = "flight_assignpark";

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            consumeMsg(QUEUE_FLIGHT_ASSIGNPARK);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }


    /**
     * 从mq中消费消息
     *
     * @param queueName
     * @throws Exception
     */
    public void consumeMsg(String queueName) throws Exception {
        LOG.info("*********从消息队列中获取机位分配结果、靠桥率结果统计数据**************");
        new Thread(() -> {
            while (true) {
                StompFrame frame;
                String messageId = "";
                StompConnection stompConnection = null;
                try {
                    String ack = "client";
                    stompConnection = jmsProducer.connectionFactory();
                    stompConnection.subscribe(queueName, ack);
                    stompConnection.keepAlive();
                    // 注意,如果没有接收到消息,
                    // 这个消费者线程会停在这里,直到本次等待超时
                    long waitTimeOut = 30000;
                    frame = stompConnection.receive(waitTimeOut);
                    Map<String, String> headers = frame.getHeaders();
                    messageId = headers.get("message-id");
                    LOG.info("消息id:{}", messageId);
                    //具体的业务处理......
                    resultService.saveResult(frame.getBody());
                    // 在ack是client标记的情况下,确认消息
                    if ("client".equals(ack)) {
                        stompConnection.ack(messageId);
                    }
                } catch (SocketTimeoutException e) {
                    LOG.error(e.getMessage());
                    continue;
                } catch (JSONException ex) {
                    LOG.error("message_id:{},数据异常:{}", messageId, ex.getMessage());
                    continue;
                } catch (Exception e) {
                    LOG.error(e.getMessage());
                    continue;
                } finally {
                    try {
                        stompConnection.disconnect();
                    } catch (Exception e) {
                        LOG.error(e.getMessage());
                    }
                }
            }
        }).start();
    }
}

 

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页