spring boot rabbitmq 配置

关于什么是消息中间件以及好处,可以参考博主之前的文章(SpringBoot整合ActiveMQ),这里就不做过多介绍 ~

一 . 简单整合

1. 添加RabbitMQ依赖

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

2. 配置application.yml

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: test
    password: 123456
#    virtual-host: /

3. 新建RabbitMQConfig

package com.example.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    // 测试队列名称
    private String testQueueName = "test_queue";
    // 测试交换机名称
    private String testExchangeName = "test_exchange";
    // RoutingKey
    private String testRoutingKey = "test_routing_key";

    /** 创建队列 */
    @Bean
    public Queue testQueue() {
        return new Queue(testQueueName);
    }
    /** 创建交换机 */
    @Bean
    public TopicExchange testExchange() {
        return new TopicExchange(testExchangeName);
    }
    /** 通过routingKey把队列与交换机绑定起来 */
    @Bean
    public Binding testBinding() {
        return BindingBuilder.bind(testQueue()).to(testExchange()).with(testRoutingKey);
    }
}

4. 新建生产者(producer)

package com.example.producer;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TestProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String queueName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", "756840349@qq.com");
        jsonObject.put("timestamp", System.currentTimeMillis());
        String jsonString = jsonObject.toJSONString();
        // 生产者发送消息的时候需要设置消息id
        Message message = MessageBuilder.withBody(jsonString.getBytes())
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
                .build();
        rabbitTemplate.convertAndSend(queueName, message);
    }
}

5. 新建消费者(consumer)

package com.example.listener;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class FanoutSmsConsumer {
	@RabbitListener(queues = "test_queue")
	public void consumeMessage(Message message) throws Exception{
		String msg = new String(message.getBody(), "UTF-8");
		JSONObject jsonObject = JSONObject.parseObject(msg);
		System.out.println("消费消息:" + jsonObject);
	}
}

6. 编写controller测试

package com.example.controller;

import com.example.producer.FanoutProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProducerController {
	@Autowired
	private TestProducer TestProducer;
	@RequestMapping("/sendMsg")
	public String sendFanout() {
		fanoutProducer.send("test_queue");
		return "success";
	}
}

浏览器访问localhost:8080/sendMsg,会返回success,并且控制台监听器会打印消息:

      

二 . 进阶场景

1. 消费者在消费消息的时候,如果消费者业务逻辑出现程序异常,这时候应该如何处理?

 

解决办法:使用消息重试机制(自带的特性,无需配置,只要出现异常就自动重试)

原理:@RabbitListener 底层使用AOP拦截,如果程序没有抛出异常,自动提交事务,如果抛出异常,则自动重试,重新消费消息

拓展①:如果一直报异常,不可能一直重试,这时候可以修改重试策略(在application.properties添加以下配置):

#开启消费者重试
spring.rabbitmq.listener.simple.retry.enabled=true
#最大重试次数(重试5次还不行则会把消息删掉,默认是不限次数的,次数建议控制在10次以内)
spring.rabbitmq.listener.simple.retry.max-attempts=5
#重试间隔时间
spring.rabbitmq.listener.simple.retry.initial-interval=3000

拓展②:如何合理选择重试机制?

          消费者获取到消息后,调用第三方接口,但接口暂时无法访问,是否需要重试?  (需要重试机制)  

          消费者获取到消息后,抛出数据转换异常,是否需要重试?(不需要重试机制,需要发布版本进行解决)

@Component
public class EamilConsumer {
	@RabbitListener(queues = "femail_queue")
	public void process(String msg) throws Exception {
		JSONObject jsonObject = JSONObject.parseObject(msg);
		String email = jsonObject.getString("email");
		String emailUrl = "http://127.0.0.1:8083/sendEmail?email=" + email;
		JSONObject result = HttpClientUtils.httpGet(emailUrl);
		if (result == null) {
			// 因为网络原因,造成无法访问,继续重试
			throw new Exception("调用接口失败!");
		}
		System.out.println("执行结束....");
	}
}

2. RabbitMQ消息确认机制ack模式(默认为手动应答,这里讲解自动应答)

① application.peoperties配置:

# 手动签收
spring.rabbitmq.listener.simple.acknowledge-mode=manual

② 修改监听器代码(在请求参数加入"@Headers Map<String, Object> headers, Channel channel"):

@Component
public class FanoutEamilConsumer {
	@RabbitListener(queues = "fanout_email_queue")
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		System.out.println(Thread.currentThread().getName() 
                    + ",msg:" + new String(message.getBody(), "UTF-8")
                    + ",messageId:" + message.getMessageProperties().getMessageId());
		// 手动ack
		Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
		// 手动签收
		channel.basicAck(deliveryTag, false);
	}
}

3. 消费者如何保证消息幂等性,不被重复消费?

① 产生原因:网络延迟传输中,消费出现异常或者是消费延迟消费,会造成MQ进行重试补偿,重试过程中,可能造成重复消费

② 解决办法1> 使用全局MessageId判断消费方使用同一个,解决幂等性    2> 或者使用业务逻辑保证唯一(比如订单号码)

生产者代码

public void send(String queueName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", "644064779");
        jsonObject.put("timestamp", System.currentTimeMillis());
        String jsonString = jsonObject.toJSONString();
        System.out.println("jsonString:" + jsonString);
        // 生产者发送消息的时候需要设置消息id
        String uuid = UUID.randomUUID() + "";
        Message message = MessageBuilder.withBody(jsonString.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
                .setMessageId(UUID.randomUUID() + "").build();
        //将messageId存入redis(在监听器判空,防止重复消费)
		stringRedisTemplate.opsForValue().set("uuid ", uuid );
        rabbitTemplate.convertAndSend(queueName, message);
    }

消费者代码

@RabbitListener(queues = "fanout_email_queue")
public void process(Message message) throws Exception {
	String messageId = message.getMessageProperties().getMessageId();
	String msg = new String(message.getBody(), "UTF-8");
	JSONObject jsonObject = JSONObject.parseObject(msg);
      
	if(!stringRedisTemplate.hasKey("meaagaeId")){
		return;//已经被消费	
	}
	String email = jsonObject.getString("email");
	String emailUrl = "http://127.0.0.1:8083/sendEmail?email=" + email;
	JSONObject result = HttpClientUtils.httpGet(emailUrl);
	//如果调用第三方邮件接口无法访问,如何实现自动重试?抛出异常即可
	if (result == null) {
		throw new Exception("调用第三方邮件服务器接口失败!");//如果走到这一行,则会自动重试
	}
	stringRedisTemplate.delete(messageId);//删除,实际开发中也可以设置为空,只需要在上面判空即可	
        //或者是走到这一行,写入数据库日志记录表,在上面if(StringUtils.equals。。中判断日志表中是否有记录即可
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值