springboot整合rabbitmq,动态创建queue和监听queue

springboot整合rabbitmq,动态创建queue和监听queue1、pom.xml添加如下依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency>…

大家好,又见面了,我是你们的朋友全栈君。

一、pom.xml添加如下依赖

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

         <!-- mq的依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
   
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

二、整合rabbitmq

   (1)在application.properties中添加mq信息

#mq的连接信息,可直接多host连接和单host连接
mq.rabbit.address=192.168.1.1:5672,192.168.1.2:5672
mq.rabbit.virtualHost=/
mq.rabbit.username=guest
mq.rabbit.password=guest
mq.rabbit.exchange.name=mq.direct

#创建queue的数量
mq.rabbit.size=2

#消费者数量
mq.concurrent.consumers=4

#每个消费者获取的最大的消息投递数量
mq.prefetch.count=100

    (2)rabbitmqConfig工具类

@Configuration
public class RabbitConfig {

    @Value("${mq.rabbit.address}")
    String address;
    @Value("${mq.rabbit.username}")
    String username;
    @Value("${mq.rabbit.password}")
    String password;
    @Value("${mq.rabbit.virtualHost}")
    String mqRabbitVirtualHost;
    @Value("${mq.rabbit.exchange.name}")
    String exchangeName;
    @Value("${mq.rabbit.size}")

    int queueSize;

    @Value("${mq.concurrent.consumers}")
    int concurrentConsumers;
    @Value("${mq.prefetch.count}")
    int prefetchCount;

    //创建mq连接
    @Bean(name = "connectionFactory")
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();

        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(mqRabbitVirtualHost);

        connectionFactory.setPublisherConfirms(true);

        //该方法配置多个host,在当前连接host down掉的时候会自动去重连后面的host
        connectionFactory.setAddresses(address);
        return connectionFactory;
    }

   //监听处理类
    @Bean
    @Scope("prototype")
    public HandleService handleService() {
        return new HandleService();
    }

     //动态创建queue,命名为:hostName.queue1【192.168.1.1.queue1】,并返回数组queue名称
    @Bean
    public String[] mqMsgQueues() throws AmqpException, IOException {
        String[] queueNames = new String[queueSize];
        String hostName = OsUtil.getHostNameForLiunx();//获取hostName
        for (int i = 1; i <= queueSize; i++) {
            String queueName = String.format("%s.queue%d", hostName, i);
            connectionFactory().createConnection().createChannel(false).queueDeclare(queueName, true, false, false, null);
            connectionFactory().createConnection().createChannel(false).queueBind(queueName, exchangeName, queueName);
            queueNames[i - 1] = queueName;
        }
        return queueNames;
    }

    //创建监听器,监听队列
    @Bean
    public SimpleMessageListenerContainer mqMessageContainer(HandleService handleService) throws AmqpException, IOException {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
        container.setQueueNames(mqMsgQueues());
        container.setExposeListenerChannel(true);
        container.setPrefetchCount(prefetchCount);//设置每个消费者获取的最大的消息数量
        container.setConcurrentConsumers(concurrentConsumers);//消费者个数
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//设置确认模式为手工确认
        container.setMessageListener(handleService);//监听处理类
        return container;
    }

}

(3)消费者

@Service
public class HandleService implements ChannelAwareMessageListener {
    private static final Logger logger = LoggerFactory.getLogger(HandleService.class);

    /**
     * @param
     * 1、处理成功,这种时候用basicAck确认消息;
     * 2、可重试的处理失败,这时候用basicNack将消息重新入列;
     * 3、不可重试的处理失败,这时候使用basicNack将消息丢弃。
     *
     *  basicNack(long deliveryTag, boolean multiple, boolean requeue)
     *   deliveryTag:该消息的index
     *  multiple:是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
     * requeue:被拒绝的是否重新入队列
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        byte[] body = message.getBody();
        logger.info("接收到消息:" + new String(body));
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(new String(body));
            if (消费成功) {
               logger.info("消息消费成功");
               channel.basicAck(message.getMessagePropertites().getDeliveryTag(),false);//确认消息消费成功     
            }else if(可重试的失败处理){
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
          } else {          //消费失败             
               channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);             
        } catch (JSONException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);//消息丢弃
            logger.error("This message:" + jsonObject + " conversion JSON error ");
        }
    }

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/146685.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • leetcode-54螺旋矩阵

    leetcode-54螺旋矩阵给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。示例 1:输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3,6,9,8,7,4,5]示例 2:输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]输出:[1,2,3,4,8,12,11,10,9,5,6,7]提示:m == matrix.lengthn == matrix[i].length1 <= m,

    2022年8月8日
    5
  • RC低通滤波器_滤波器的基本原理

    RC低通滤波器_滤波器的基本原理先来几个不错的资源链接:1.RC滤波器截止频率在线计算器:http://www.eechina.com/tools/rc_filter_cutoff_frequency.html2.详谈一阶RC低通滤波器如何过滤高频噪声(网上不错的一个帖子)http://www.elecfans.com/instrument/631912.html3.【滤波器学习笔记】一阶RC低通滤波(下页截图来源)…

    2022年4月19日
    72
  • Linux服务配置 DNS服务器配置「建议收藏」

    Linux服务配置 DNS服务器配置「建议收藏」一、什么是DNS服务器DNS(DomainNameSystem):域名系统用于IP和域名的解析产生原因:上网需要IP,而IP不好记忆,用英文字母表示的域名便于记忆。二、CentOS7配置DNS服务器过程1.准备服务器、客户端服务器IPDNS服务器IP=192.168.222.110客户端IP=192.168.222.137测试机IP=192.168.222.1002.DNS服务器配置(192.168.222.110)改网卡vi/etc/s

    2022年6月4日
    42
  • goland2021.7.20激活码_在线激活

    (goland2021.7.20激活码)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月21日
    43
  • halcon联合C#_halcon调用自己的模型

    halcon联合C#_halcon调用自己的模型20210221版最新C#联合halcon开发框架源码,傻瓜式拖拽,匹配,测量,条码识别,ocr,定位引导,对位等,支持plc通讯,支持相机sdk无缝对接

    2025年7月2日
    3
  • 矩阵可逆的充要条件证明_两个矩阵相乘所得矩阵的秩

    矩阵可逆的充要条件证明_两个矩阵相乘所得矩阵的秩矩阵可逆的充要条件有很多,在此进行总结。设A为n阶矩阵,则矩阵A可逆的充要条件为:|A|≠0;r(A)=n;A的列(行)向量组线性无关;A的特征值中没有0;A可分解为若干初等矩阵的乘积.

    2022年8月5日
    21

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号