spring boot 项目集成ActiveMQ

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();
        }

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

woniyu123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值