SpringBoot集成Rabbit实例-RabbitMq学习笔记(三)

本文介绍了SpringBoot如何集成RabbitMQ,包括消息发送接收流程和具体实现步骤,如添加依赖、配置、创建config类和消息发送类,以及通过测试类验证消息收发功能。
摘要由CSDN通过智能技术生成
一、消息发送接收流程

最近研究了一下RabbitMq的发送接收消息流程。其过程简言之,就是生产者直接发给Exchange,通过Exchange来进行匹配转发到队列,消费者直接监听该队列即可接收到消息。当然,这个Exchange需要在生产消息之前进行队列和路由绑定,以确定匹配规则和向哪个队列发送。比如说,生产者A要发送消息,最终要被消费者B消费,那么就要经过下面步骤:

1)A生产消息,发送给服务器端的Exchange
2)Exchange收到消息,根据ROUTINKEY,将消息转发给匹配的Queue1
3)Queue1收到消息,将消息发送给订阅者B
4)B收到消息,发送ACK给队列确认收到消息
5)Queue1收到ACK,删除队列中缓存的此条消息
二、实现SpringBoot集成RabbitMq

下面实现了SpringBoot集成RabbitMq的流程

1.增加maven依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.配置文件
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtualHost=/
3.config类:RabbitMqConfig
package com.wj.rabbit.config;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class RabbitMqConfig {
    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.port}")
    private String port;
    @Value("${spring.rabbitmq.username}")
    private String userName;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtualHost}")
    private String vitualHost;
        public static final String EXCHANGE   = "exchange2";
        public static final String ROUTINGKEY = "spring-boot-routingKey";
  //创建连接工厂
        @Bean
        public ConnectionFactory connectionFactory() {
            CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
            String adress = host+":"+port;
            connectionFactory.setAddresses(adress);
            connectionFactory.setUsername(userName);
            connectionFactory.setPassword(password);
            connectionFactory.setVirtualHost(vitualHost);
            connectionFactory.setPublisherConfirms(true); //必须要设置
            return connectionFactory;
        }
        //该类可以说是Rabbit的发送工具类
        @Bean
        @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
        //必须是prototype类型
        public RabbitTemplate rabbitTemplate() {
            RabbitTemplate template = new RabbitTemplate(connectionFactory());
            return template;
        }

        /**
         * 针对消费者配置
         * 1. 设置交换机类型
         * 2. 将队列绑定到交换机
         *
         *
         FanoutExchange: 将消息分发到所有的绑定队列,无routingkey的概念
         HeadersExchange :通过添加属性key-value匹配
         DirectExchange:按照routingkey分发到指定队列
         TopicExchange:多关键字匹配
         */
        @Bean
        public DirectExchange defaultExchange() {
            return new DirectExchange(EXCHANGE,false,true);
        }
      /* @Bean
       public TopicExchange defaultExchange(){
           return new TopicExchange(EXCHANGE);
       }*/

        @Bean
        public Queue queue() {
            return new Queue("spring-boot-queue2", true,true,false); //队列持久(可以通过不同参数,对队列的属性进行设置,具体属性含义可以参考上一篇博文:RabbitMq学习笔记(二))
        }

        @Bean
        public Binding binding() {//绑定
            return BindingBuilder.bind(queue()).to(defaultExchange()).with(RabbitMqConfig.ROUTINGKEY);
        }

        @Bean
        public SimpleMessageListenerContainer messageContainer() {
            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
            container.setQueues(queue());
            container.setExposeListenerChannel(true);
            container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式为手工确认,保证消息能被消费者接收到
            container.setMessageListener(new ChannelAwareMessageListener() {
                @Override
                public void onMessage(Message message, Channel channel) throws Exception {
                    byte[] body = message.getBody();
                    System.out.println("receive msg : " + new String(body));
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
                }
            });
            return container;
        }
}
4.消息发送类:Producer
package com.wj.rabbit.producer;

import com.wj.rabbit.config.RabbitMqConfig;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class Producer {

    private RabbitTemplate rabbitTemplate;
    /**
     * 构造方法注入
     */
    @Autowired
    public Producer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendMsg(String content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE, RabbitMqConfig.ROUTINGKEY, content, correlationId);
    }
}
5.测试类:RabbitApplicationTests
package com.wj.rabbit;

import com.wj.rabbit.producer.Producer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitApplicationTests {
    @Autowired
	private Producer send;
	@Test
	public void send(){
		for (int i = 0; i <100 ; i++) {
			send.sendMsg("hello~"+i);
		}
	}

}

直接执行测试类中的send方法,即可实现消息的收发。同时,也可以在管理端实时监控。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值