1. RabbitMQ简介
1.1. RabbitMQ
RabbitMQ是由Erlang(爱立信公司)语言开发,实现Advanced Message Queuing Protocol (AMQP高级消息队列协议)的消息中间件。消息中间件主要用于组件之间的解耦,消息的发送者无需知道消息使用者的存在,反之亦然。
1.2. 结构图
• Broker:消息队列服务器实体,例如RabbitMQ服务
• Vhost:虚拟主机,默认为“/”,一个broker里可以有多个vhost,区分不同用户权限,类似java的命令空间
• Connection:应用程序与broker连接,可有多个连接
• Channel:消息通道,connection中可建立多个channel,每个channel代表一个会话任务,所有操作都在channel中进行。
• Exchange:消息交换机,channel中可有多个,用于投递消息。应用程序发送消息时先把消息给交换机,由交换机投递给队列,不是直接给队列。
类型有三种:fanout(广播)、Direct(处理路由键,轮播实现)、Topic(支持消息模糊匹配)
• Queue:队列,用于存放消息
• Message:消息,应用程序需要发送的数据
• Bind:根据routingKey绑定exchange与queue规则,决定消息发送的方向
1.3. 对象间关系
2. rabbitMQ与spring集成
使用spring封装的rabbitmq的 https://github.com/spring-projects/spring-amqp 做集成。
2.1. 发送消息Producer
发送接口
public interface SimpleMQProducer {
/**
* 发送消息至MQ
*/
public void sendDataToMQ(Object message);
/**
* 发送消息至MQ
*/
public void sendDataToMQ(Object message, String msgid);
}
发送接口实现
public class SmartMQProducer implements InitializingBean,SimpleMQProducer{
protected final Loggerx logger = Loggerx.getLogger("dao");
protected RabbitTemplate rabbitTemplate = new RabbitTemplate();
protected String queue;
protected String exchange;
protected String routingKey;
protected ConnectionFactory connectionFactory;
protected MessageConverter messageConverter;
protected RetryTemplate retryTemplate;
protected ConfirmCallback confirmCallback;
protected ReturnCallback failedCallback;
public RabbitTemplate getRabbitTemplate() {
return rabbitTemplate;
}
public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void setQueue(String queue) {
this.queue = queue;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void setMessageConverter(MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
public void setRetryTemplate(RetryTemplate retryTemplate) {
this.retryTemplate = retryTemplate;
}
public void setConfirmCallback(ConfirmCallback confirmCallback) {
this.confirmCallback = confirmCallback;
}
public void setFailedCallback(ReturnCallback failedCallback) {
this.failedCallback = failedCallback;
}
@Override
public void sendDataToMQ(Object message) {
CorrelationData correlationId = null;
try {
correlationId = new CorrelationData(GUID.genTxNo(25));
} catch (Exception e) {
logger.error(LogType.EX, "产生消息id失败",e);
correlationId = new CorrelationData(UUID.randomUUID().toString());
}
this.rabbitTemplate.convertAndSend(this.routingKey, message, correlationId);
logger.info(LogType.EX, "发送到MQ的消息内容["+JsonUtil.toJSONString(message)+"],消息ID["+correlationId.getId()+"]");
}
@Override
public void sendDataToMQ(Object message, String msgid) {
CorrelationData correlationId = new CorrelationData(msgid);
this.rabbitTemplate.convertAndSend(this.routingKey, message, correlationId);
logger.info