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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • sklearn KFold()

    最近实践过程中遇到需要KFold()记录一下,以便日后查阅KFold()在sklearn中属于model_slection模块fromsklearn.model_selectionimportKFoldKFold(n_splits=’warn’,shuffle=False,random_state=None)参数:n_splits表示划分为几块(至少是2)shuffle…

    2022年4月5日
    89
  • dos命令打开文件夹_dos命令开启无线网络

    dos命令打开文件夹_dos命令开启无线网络如何用dos命令查看文件?首先通过cd进入文件所在目录,然后执行start命令即可。【startfileName】:打开文件

    2022年10月14日
    0
  • 上海踩踏事件所想,莫把应急预案当摆设

    2014年12月31日,人们还沉浸在辞旧迎新的气氛中,微信上还在互相发着红包,微博上突然出现了上海外滩踩踏事件的消息。这个事件突发而至,36人死亡、47人受伤的结果,让我们在2015年的第一天“新年快乐”这几个字说的有些有气无力,消减了许多喜庆气氛。踩踏事件在我国已经发生过多次,上海发生过,北京也发生过,就在十年前,也是辞旧迎新的日子,北京密云也发生了踩踏事故,也是三十多条人命的代价!踩踏…

    2022年4月10日
    56
  • python语言变量命名规则有什么_Python变量命名规则(超级详细)

    python语言变量命名规则有什么_Python变量命名规则(超级详细)Python需要使用标识符给变量命名,其实标识符就是用于给程序中变量、类、方法命名的符号(简单来说,标识符就是合法的名字)。Python语言的标识符必须以字母、下画线(_)开头,后面可以跟任意数目的字母、数字和下画线(_)。此处的字母并不局限于26个英文字母,可以包含中文字符、日文字符等。由于Python3支持UTF-8字符集,因此Python3的标识符可以使用UTF-8…

    2022年5月3日
    127
  • 【RPC Dubbo】dubbo负载均衡策略

    【RPC Dubbo】dubbo负载均衡策略文章目录前言参考前言在上一篇博客中,介绍了zookeeper作为dubbo的注册中心是如何工作的,有一个很重要的点,我们的程序是分布式应用,服务部署在几个节点(服务器)上,当消费者调用服务时,zk返回给dubbo的是一个节点列表,但是dubbo只会选择一台服务器,那么它究竟会选择哪一台呢?这就是dubbo的负载均衡策略了,本篇博客就来聚焦dubbo的负载均衡策略。参考dubbo负载均衡策略…

    2022年7月11日
    16
  • 玩客云 青龙面板_青龙京东签到

    玩客云 青龙面板_青龙京东签到玩客云安装青龙面板实现京东签到薅羊毛

    2022年9月18日
    0

发表回复

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

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