如何优雅的使用activeMQ

首先,我是一个activemq的初学者,学习期间也阅读了大量的博客,很感谢csdn博客给我的灵感,希望我的创作能对大家有所帮助

1.添加maven依赖包,话不多说,直接上代码

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>

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

2.activemq的一些相关配置

server:
  port: 8083


#activcemq的连接池
com:
  example:
    mqUrl:  tcp://localhost:61616
    #是否放在内存中:
    in-memery: false
    pool:
      #是否启用连接池
      enable: true
      #最大连接数
      maxConn: 200
    user: admin
    password: admin




#消息队列的名称
queue:
  example:
    queue1: queue1
    queue2: queue2
    queue3: queue3


#主题队列名称
topic:
  example:
    topic1: topic1
    topic2: topic2
    topic3: queue3

3.通过工厂的方法创建activemq连接

package com.example.activemq.factory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @className:@MqFactory
 * @Description:TODO
 * @Author:
 * @Version:1.0
 **/
@Configuration
public class MqFactory {
    //tcp连接路径
    @Value("${com.example.mqUrl}")
    private String brokerUrl;
    //是否放在内存
    @Value("${com.example.in-memery}")
    private String inMemery;
    //是否启用连接池
    @Value("${com.example.pool.enable}")
    private Boolean enable;
    //最大连接数
    @Value("${com.example.pool.maxConn}")
    private Integer maxConn;
    //用户名
    @Value("${com.example.user}")
    private String user;
    //密码
    @Value("${com.example.password}")
    private String password;
    /**
     * 创建工厂
     */
    @Bean
    public ActiveMQConnectionFactory connactivemq(){
        ActiveMQConnectionFactory factory =  new ActiveMQConnectionFactory(brokerUrl);
        factory.setTransactedIndividualAck(true);
        factory.setMaxThreadPoolSize(maxConn);
        factory.setUserName(user);
        factory.setPassword(password);
        factory.setStatsEnabled(enable);
        return factory;
    }










}
package com.example.activemq.factory;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJcaListenerContainerFactory;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.stereotype.Component;

/**
 * @className:@MqListener
 * @Description:TODO
 * @Author: 点对点监听bean注入
 * @Version:1.0
 **/
@Component
public class MqListener {

    @Autowired
    private MqFactory mqFactory;

    /**
     * 监听队列的bean
     * @return
     */
    @Bean
    public JmsListenerContainerFactory<?> jmsFactoryQueue(){
        DefaultJmsListenerContainerFactory defaultFactory = new DefaultJmsListenerContainerFactory();
        defaultFactory.setConnectionFactory(mqFactory.connactivemq());
        return defaultFactory;

    }

    /**
     * 监听主题
     * @return
     */
    @Bean
    public JmsListenerContainerFactory<?> jmsFactoryTopic(){
        DefaultJmsListenerContainerFactory defaultFactory = new DefaultJmsListenerContainerFactory();
        defaultFactory.setConnectionFactory(mqFactory.connactivemq());
        defaultFactory.setPubSubDomain(true);
        return defaultFactory;

    }

}

4.分别创建多个队列bean和主题bean.

package com.example.activemq.factory;

import com.example.activemq.model.QueueConfig;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;

/**
 * @className:@MqQueueList
 * @Description:TODO创建点对点队列
 * @Author:
 * @Version:1.0
 **/
@Configuration
@EnableJms
public class MqQueueList {


    @Autowired
    private QueueConfig queueConfig;
    @Bean
    public javax.jms.Queue queue1(){
       return new ActiveMQQueue(queueConfig.getQueue1());
    }
    @Bean
    public javax.jms.Queue queue2(){
        return new ActiveMQQueue(queueConfig.getQueue2());
    }
    @Bean
    public javax.jms.Queue queue3(){
        return new ActiveMQQueue(queueConfig.getQueue3());
    }



}
package com.example.activemq.factory;

import com.example.activemq.model.TopicConfig;
import org.apache.activemq.broker.region.Topic;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;


/**
 * @className:@MqTopic
 * @Description:TODO
 * @Author: 发布订阅模式,发布主题
 * @Version:1.0
 **/
@Configuration
@EnableJms
public class MqTopic {
    @Autowired
    private TopicConfig topicConfig;
    @Bean
    public javax.jms.Topic topic1(){
      return   new ActiveMQTopic(topicConfig.getTopic1());
    }
    @Bean
    public javax.jms.Topic topic2(){
        return   new ActiveMQTopic(topicConfig.getTopic2());
    }
    @Bean
    public javax.jms.Topic topic3(){
        return   new ActiveMQTopic(topicConfig.getTopic3());
    }
}

5.以下是两个模型类,创建模型类获取配置文件的值,减少代码的冗余。

package com.example.activemq.model;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @className:@QueueConfig
 * @Description:TODO
 * @Author:
 * @Version:1.0
 **/
@Data
@Configuration
public class QueueConfig {

    @Value("${queue.example.queue1}")
    private String queue1;
    @Value("${queue.example.queue2}")
    private String queue2;
    @Value("${queue.example.queue3}")
    private String queue3;
}
package com.example.activemq.model;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @className:@QueueConfig
 * @Description:TODO
 * @Author:
 * @Version:1.0
 **/
@Data
@Configuration
public class TopicConfig {

    @Value("${topic.example.topic1}")
    private String topic1;
    @Value("${topic.example.topic2}")
    private String topic2;
    @Value("${topic.example.topic3}")
    private String topic3;
}

6.下面是测试提供者的消息发送功能。

package com.example.activemq.producer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.activemq.factory.MqTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.Queue;
import javax.jms.Topic;
import java.util.HashMap;
import java.util.Map;

/**
 * @className:@ProducerController
 * @Description:TODO
 * @Author:
 * @Version:1.0
 **/
@RestController
public class ProducerController {
    @Autowired
    private Queue queue1;
    @Autowired
    private Queue queue2;
    @Autowired
    private Queue queue3;
    @Autowired
    private Topic topic1;
    @Autowired
    private Topic topic2;
    @Autowired
    private Topic topic3;
    @Autowired
    private JmsMessagingTemplate mesTemplate;

    @GetMapping("/sendQueue")
    public String getQueueContent(){
        JSONObject sendData = new JSONObject();
        sendData.put("msg","发送成功");
        sendData.put("data","我是queue");
        sendData.put("code",200);
        mesTemplate.convertAndSend(queue1,sendData.toJSONString());
        mesTemplate.convertAndSend(queue2,sendData.toJSONString());
        mesTemplate.convertAndSend(queue3,sendData.toJSONString());
        return "ok,send Queue Success";
    }


    @GetMapping("/sendTopic")
    public String getTopicContent(){
        JSONObject sendData = new JSONObject();
        sendData.put("msg","发送成功");
        sendData.put("data","我是topic");
        sendData.put("code",200);
        mesTemplate.convertAndSend(topic1, sendData.toJSONString());
        mesTemplate.convertAndSend(topic2,sendData.toJSONString());
        mesTemplate.convertAndSend(topic3,sendData.toJSONString());
        return "ok,send Topic Success";
    }


}

7.监听接收消息类

package com.example.activemq.consumer;

import com.example.activemq.model.QueueConfig;
import com.example.activemq.model.TopicConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

/**
 * @className:@JMSListenerConcumer
 * @Description:监听发送来的消息
 * @Author:
 * @Version:1.0
 **/
@Component
@EnableJms
public class JMSListenerConcumer {

    private Logger logger = LoggerFactory.getLogger(JMSListenerConcumer.class);
    @JmsListener(destination ="${queue.example.queue1}",containerFactory = "jmsFactoryQueue")
    public void recieveQueue1(String msg){
        logger.info("queue1 接收的消息 {}",msg);
    }


    @JmsListener(destination ="${queue.example.queue2}",containerFactory = "jmsFactoryQueue")
    public void recieveQueue2(String msg){
        logger.info("queue2 接收的消息 {}",msg);
    }
    @JmsListener(destination ="${queue.example.queue3}",containerFactory = "jmsFactoryQueue")
    public void recieveQueue3(String msg){
        logger.info("queue3 接收的消息 {}",msg);
    }

    @JmsListener(destination ="${topic.example.topic1}",containerFactory = "jmsFactoryTopic")
    public void recieveTopic1(String msg){
        logger.info("topic1 接收的消息 {}",msg);
    }
    @JmsListener(destination ="${topic.example.topic2}",containerFactory = "jmsFactoryTopic")
    public void recieveTopic2(String msg){
        logger.info("topic2 接收的消息 {}",msg);
    }
    @JmsListener(destination ="${topic.example.topic3}",containerFactory = "jmsFactoryTopic")
    public void recieveTopic3(String msg){
        logger.info("topic3 接收的消息 {}",msg);
    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

心之所想,行则将至

创作不易,希望大家多多鼓励支持

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

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

打赏作者

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

抵扣说明:

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

余额充值