关于spring boot 集成rabbitmq 相关学习笔记

本文介绍了如何在项目中配置并使用RabbitMQ消息中间件,包括Maven依赖配置、服务器配置、生产者与消费者的实现方式及具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先引入 rabbitmq 相关 maven 配置

<!--消息队列模块-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-amqp</artifactId>

</dependency>

2.关于rabbitmq的相关配置(本项目采用.properties配置)

 

#服务器名称
spring.application.name=service-bank-rabbitmq
#服务器地址
spring.rabbitmq.host=192.168.1.36
#服务器端口
spring.rabbitmq.port=5672
#用户名
spring.rabbitmq.username=admin
#密码
spring.rabbitmq.password=admin
#指定连接到broker的Virtual host.
spring.rabbitmq.virtual-host=/
# 开启发布确认机制
spring.rabbitmq.publisher-confirms=true
#设置消费者必须手动ack进行消息确认
spring.rabbitmq.listener.acknowledge-mode=MANUAL
#是否在启动时就启动mq,默认: true)
spring.rabbitmq.listener.auto-startup=true
#是否创建AmqpAdmin bean. 默认为: true)
#spring.rabbitmq.dynamic
#指定最小的消费者数量.
#spring.rabbitmq.listener.concurrency
#指定最大的消费者数量.
#spring.rabbitmq.listener.max-concurrency
#指定一个请求能处理多少个消息,如果有事务的话,必须大于等于transaction数量.
#spring.rabbitmq.listener.prefetch
#指定一个事务处理的消息数量,最好是小于等于prefetch的数量.
#spring.rabbitmq.listener.transaction-size
#是否开始SSL,默认: false)
#spring.rabbitmq.ssl.enabled
#指定持有SSL certificate的key store的路径
#spring.rabbitmq.ssl.key-store
#指定访问key store的密码.
#spring.rabbitmq.ssl.key-store-password
#指定持有SSL certificates的Trust store.
#spring.rabbitmq.ssl.trust-store
#指定连接到broker的Virtual host.
#spring.rabbitmq.virtual-host
3.生产者相关

首先开启初始化配置

在启动 生产者时将交换机(Topic) ,队列, 以及交换机与队列的绑定进行初始化

    /**
     * @Author:chenhf
     * @Description: 主题型Topic
     * @Date:下午5:49 2017/10/23
     * @param
     * @return
     */
    @Bean
    TopicExchange contractTopicExchangeDurable(){
        //第二个表示是否持久化第三个表示是否自动删除
        TopicExchange contractTopicExchange = new TopicExchange(RabbitMqEnum.Exchage.EXCHAGE_TOPIC_TEST.getCode(),true ,false );
        return contractTopicExchange;
    }

    //在此可以定义队列
    @Bean
    Queue queueTopicTestA(){
        //第二个参数是否持久化第三个参数是否独有第四个参数是否自动删除
        Queue queue = new Queue(RabbitMqEnum.Queue.EXCHAGE_TOPIC_A.getCode(),true,false,false);
        return queue;
    }

    @Bean
    Queue queueTopicTestB(){
        //第二个参数是否持久化第三个参数是否独有第四个参数是否自动删除
        Queue queue = new Queue(RabbitMqEnum.Queue.EXCHAGE_TOPIC_B.getCode(),true,false,false);
        return queue;
    }

    @Bean
    Queue queueTopicTestC(){
        //第二个参数是否持久化第三个参数是否独有第四个参数是否自动删除
        Queue queue = new Queue(RabbitMqEnum.Queue.EXCHAGE_TOPIC_C.getCode(),true,false,false);
        return queue;
    }

    //topic binding1
    @Bean
    Binding bindingQueueTopicTestA(Queue queueTopicTestA, TopicExchange exchange){
        Binding binding = BindingBuilder.bind(queueTopicTestA).to(exchange).with(RabbitMqEnum.QueueKey.TOPIC_A.getCode());
        return binding;
    }

    @Bean
    Binding bindingQueueTopicTestB(Queue queueTopicTestB, TopicExchange exchange){
        Binding binding = BindingBuilder.bind(queueTopicTestB).to(exchange).with(RabbitMqEnum.QueueKey.TOPIC_B.getCode());
        return binding;
    }

    @Bean
    Binding bindingQueueTopicTestC(Queue queueTopicTestC, TopicExchange exchange){
        Binding binding = BindingBuilder.bind(queueTopicTestC).to(exchange).with(RabbitMqEnum.QueueKey.TOPIC_C.getCode());
        return binding;
    }
}

4.生产者 采用 utils 形式开发

import com.fuqin.model.RabbitMqEnum;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;

@Component
public class RabbitUtils {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //rabbitTemplate和confirmCallback保持一致
    private static  RabbitTemplate.ConfirmCallback confirmCallback;

    public void sendMessage(String msg) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        String obj = "生产者发送消息"+msg;
        rabbitTemplate.setMandatory(true);
        if(null == confirmCallback){
            confirmCallback = new RabbitTemplate.ConfirmCallback() {
                @Override
                public void confirm(CorrelationData correlationData, boolean b, String s) {
                    if(b){
                        System.out.println("发送成功");
                    }else{
                        System.out.println("发送失败从新发送");
                    }
                }
            };
        }
        this.rabbitTemplate.setConfirmCallback(confirmCallback);
        //测试topic模式下向不同队列批次投递消息共三个队列topicA topicB topicC
        //向topicA.topicB投递消息
        this.rabbitTemplate.convertAndSend(RabbitMqEnum.Exchage.EXCHAGE_TOPIC_TEST.getCode(),"topicA.topicB" , obj, correlationData);
        //向topicB.topicC投递消息
        this.rabbitTemplate.convertAndSend(RabbitMqEnum.Exchage.EXCHAGE_TOPIC_TEST.getCode(),"topicB.topicC" , obj+2222, correlationData);
    }
}

5.客户端调用

  rabbitUtils.sendMessage("hello word !");

6.消费端

消费端直接开启监听即可

 

package com.fuqin.rabbitmq.sender;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class ReceiverList {

    @RabbitHandler
    @RabbitListener(queues = "exchage_topic_A")
    public void procesA(String hello, Message message, Channel channel)throws IOException {
        channel.queueDeclare("exchage_topic_A", true, false, false, null);
        System.out.println("Receiver ---A: " + hello);
    }


    @RabbitHandler
    @RabbitListener(queues = "exchage_topic_B")
    public void procesB(String hello, Message message, Channel channel) throws IOException{
        // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。
        channel.queueDeclare("exchage_topic_B", true, false, false, null);
        System.out.println("Receiver ---B: " + hello);
    }

    @RabbitHandler
    @RabbitListener(queues = "exchage_topic_C")
    public void procesC(String hello, Message message, Channel channel) throws IOException {
        // 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。
        channel.queueDeclare("exchage_topic_C", true, false, false, null);
        System.out.println("Receiver ---C : " + hello);
        // 确认成功消费,否则消息会转发给其他的消费者,或者进行重试
        System.out.println("----- received" + message.getMessageProperties());
        try {
            //确认消息成功消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch ( IllegalArgumentException e) {
            System.out.println("------ err"+ e.getMessage());
            //ack返回false,并重新回到队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }

    }
}

7.关于rabbitmq 相关资料百度查找即可 建议学习mq 之前首先了解mq 的专用名词

8.附上rabbitmq CentOS6.7 部署文档

rabbitmq部署文档

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值