首先我们得了解RabbitMQ 是做什么用的,然后对其下手,RabbitMQ 是一个消息中间件框架。现在市场得主流,基本都用的RabbitMQ 进行做消息队列等
它是一个什么样得框架呢,那我说道说道吧,举个例子吧,比如:你老爸在家种田收的稻谷,然后呢,你老爸是不是要把它卖给加工厂或粮仓。经过加工后,
随其卖给各地大城市得超市等地方,其后有我们进行购买消费。如图:
我们用到的 RabbitMQ 也是类似于一个流程:
上图可以说明一个原因:如A、B、C服务的消息发送给生产者进行去生产,然后消费进行消费给A1、B1、C1服务提供给他们消费,A1、B1、C1随他们消费A、B、C一个服务或多个服务
反正这个消息我RabbitMQ只是一个传达消息的人。RabbitMQ他起到的作用就是解耦,把耦合度降到最低。有一句话说来着,叫高内聚,低耦合。就是说把所有消息聚合起来,然后提供个每一个服务去进行读取所需要的东西。RabbitMQ 他的好处就是可以持久化,解耦,削峰等。
话不多说,上代码:
1、首先是加依赖:
<!-- RabbitMQ 必须-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- jackson 你自己选择-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
2、yml文件的配置
spring:
rabbitmq:
addresses: 127.0.0.1:5672,127.0.0.1:5673 #MQ集群
#host: 127.0.0.1
#port: 5672
username: root
password: root
#virtual-host: /demo
#listener: #手动提交消息
# simple:
# acknowledge-mode: manual
# direct:
# acknowledge-mode: manual
publisher-confirm-type: correlated #确认消息已发送到交换机(Exchange)
publisher-returns: true #确认消息已发送到队列(Queue)
3、MQconfig配置
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
/**
* RabbitMQ 配置
*/
@Configuration
@AutoConfigureAfter(RabbitMQConfig.class)
public class RabbitMQConfig {
/**
* 将自定义的消息类序列化成json格式,再转成byte构造 Message
*
* @param connectionFactory
* @return
*/
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
return rabbitTemplate;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}
}
4、定义常量类:
public class RabbitMQConstants {
//------------------------------------交换机------------------------------------
public static final String TOPIC_EXCHANGE_DEFAULTNAME = "topic.exchange";
public static final String DELAY_EXCHANGE_DEFAULTNAME = "delay.exchange";
//public static final String FANOUT_EXCHANGE_DEFAULTNAME = "fanout.exchange";
//------------------------------------队列--------------------------------------
public static final String TOPIC_QUEUE_VIDEORING_VERIFY = "topic.queue.verify";
//------------------------------------RoutingKey--------------------------------
public static final String ROUTINGKEY_FOR_VIDEORING_VERIFY = "zkt.videoring.verify";
//-------------------------------------DLX-----------------------------------
public static final String DLX_EXCHANGE = "dlx.exchange";
public static final String DLX_QUEUE = "dlx.queue";
public static final String ROUTINGKEY_FOR_DLX = "dlx.msg";
}
5、RabbitTopicConfig 主题配置
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RabbitTopicConfig {
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(RabbitMQConstants.TOPIC_EXCHANGE_DEFAULTNAME, true, false);
}
@Bean
public Queue videoRingVerifyTopicQueue() {
Map<String, Object> params = new HashMap<>();
params.put("x-dead-letter-exchange", RabbitMQConstants.DLX_EXCHANGE);
params.put("x-dead-letter-routing-key", RabbitMQConstants.ROUTINGKEY_FOR_DLX);
return new Queue(RabbitMQConstants.TOPIC_QUEUE_VIDEORING_VERIFY, true, false, false, params);
}
@Bean
Binding bindingVideoRingVerifyTopicQueue() {
return BindingBuilder.bind(videoRingVerifyTopicQueue())
.to(topicExchange())
.with(RabbitMQConstants.ROUTINGKEY_FOR_VIDEORING_VERIFY);
}
}
6、RabbitDirectConfig交换机
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* DLX 交换机
*/
@Configuration
public class RabbitDirectConfig {
/**
* MQ DLX交换机
*
* @return DirectExchange
*/
@Bean
public DirectExchange dlxExchangeZkt() {
return new DirectExchange(RabbitMQConstants.DLX_EXCHANGE_ZKT, true, false);
}
@Bean
public Queue zktDlxQueue() {
return new Queue(RabbitMQConstants.DLX_QUEUE_ZKT, true);
}
/**
* 队列绑定交换机
*
* @return
*/
@Bean
public Binding binding() {
return BindingBuilder.bind(zktDlxQueue())
.to(dlxExchangeZkt())
.with(RabbitMQConstants.ROUTINGKEY_FOR_DLX);
}
}
7、RabbitDelayConfig 延迟配置
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RabbitDelayConfig {
/**
* 延迟交换机
*/
@Bean//("delayExchange")
public CustomExchange delayExchange() {
Map<String, Object> args = new HashMap<>(1);
args.put("x-delayed-type", "direct"); //direct
return new CustomExchange(RabbitMQConstants.DELAY_EXCHANGE_DEFAULTNAME, "x-delayed-message", true, false, args);
}
/**
* 延迟队列
*/
@Bean//("bizUnsubscribeTopicQueue")
public Queue bizUnsubscribeTopicQueue() {
Map<String, Object> params = new HashMap<>();
params.put("x-dead-letter-exchange", RabbitMQConstants.DLX_EXCHANGE_ZKT);
params.put("x-dead-letter-routing-key", RabbitMQConstants.ROUTINGKEY_FOR_DLX);
return new Queue(RabbitMQConstants.DELAY_QUEUE_BIZ_UNSUBSCRIBE, true, false, false, params);
}
/**
* 将延迟队列通过routingKey绑定到延迟交换器
*/
@Bean
Binding bindingBizUnsubscribeTopicQueue() {
return BindingBuilder.bind(bizUnsubscribeTopicQueue())
.to(delayExchange())
.with(RabbitMQConstants.ROUTINGKEY_FOR_BIZ_UNSUBSCRIBE).noargs();
}
}
8、BaseProvider 基础的生产者
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
public class BaseProvider implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {
private static final Logger logger = LoggerFactory.getLogger(BaseProvider.class);
public BaseProvider(RabbitTemplate rabbitTemplate) {
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnsCallback(this);
}
/**
* 消息发送到Exchange时的回调
*
* @param correlationData
* @param ack
* @param cause
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
if (!ack) {
logger.error("provider send exchange fail, correlationData:{}, ack:{}, cause:{}", correlationData, ack, cause);
}
}
/**
* 消息发送到Queue失败时的回调
*
* @param returnedMessage
*/
@Override
public void returnedMessage(ReturnedMessage returnedMessage) {
logger.error("provider send queue fail, exchange:{}, route:{}, replyCode:{}, replyText:{}, message:{}",
returnedMessage.getExchange(),
returnedMessage.getRoutingKey(),
returnedMessage.getReplyCode(),
returnedMessage.getReplyText(),
returnedMessage.getMessage());
}
}
9、涉及业务操作:BizOrder 是封装接收发送消息的请求参数实体
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 BizOrderProvider extends BaseProvider {
private static final Logger logger = LoggerFactory.getLogger(BizOrderProvider.class);
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 构造方法注入rabbitTemplate
*/
@Autowired
public BizOrderProvider(RabbitTemplate rabbitTemplate) {
super(rabbitTemplate);
this.rabbitTemplate = rabbitTemplate;
}
/**
* 发送实体类消息
*/
public boolean sendMessage(BizOrder message) {
try {
CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_EXCHANGE_DEFAULTNAME,
RabbitMQConstants.ROUTINGKEY_FOR_BIZ_ORDER,
message, correlationId);
logger.info("bizorder-provider send mq success, message:{}", message.toString());
return true;
} catch (Exception e) {
logger.error("bizorder-provider send mq error:{}, message:{}", e.getMessage(), message.toString(), e);
return false;
}
}
}
一个生产者就是该流程一路下来的。因时间紧急这里只弄了生产者的案例,消费者没有弄,下次有时间我把消费者加上。如果有帮到你帮我点个赞谢谢,不清楚的话可以给我留言,我看到了第一时间回复,上面贴的代码不是完整的有些做了删减,主要功能还是可以的,稍等变动一下即可