您的位置:首页 > 编程语言 > Java开发

springboot + rabbitmq实现消息的发送与消费

Z_xiansheng11 2020-07-21 04:15 543 查看 https://blog.csdn.net/z_xiansh

springboot + rabbitmq实现消息的发送与消费

导入依赖

<!-- rabbitmq依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置rabbitmq地址

在application.yal中添加以下代码

spring:
#rabbitmq数据源配置
rabbitmq:
host: 127.0.0.1   #  rabbitmq安装url
port: 5672
username: guest
password: guest
publisher-confirms: true    #  消息发送到交换机确认机制,是否确认回调

添加配置类

RabbitMqConfig.java

package com.hegoo.device.config;

import com.hegoo.device.constant.TopicPrefix;
import com.hegoo.device.rabbitmq.mqcallback.MsgSendConfirmCallBack;
import com.hegoo.device.service.IotDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;

/**
* @author zhangyr
* @date 2020/5/13 14:32
* @description RabbitMq配置
*/
@Configuration
@Slf4j
public class RabbitMqConfig {

/** 消息交换机的名字*/
public static final String EXCHANGE1 = TopicPrefix.UPLOAD_DATA;
/** 消息交换机的名字*/
public static final String EXCHANGE2 = TopicPrefix.UPDATE_STATUS;

@Autowired
private QueueConfig queueConfig;
@Autowired
private ExchangeConfig exchangeConfig;
@Autowired
private IotDeviceService iotDeviceService;
/**
* 连接工厂
*/
@Autowired
private ConnectionFactory connectionFactory;
/**
* 定义rabbit template用于数据的接收和发送
* @return
*/
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
/**若使用confirm-callback或return-callback,
* 必须要配置publisherConfirms或publisherReturns为true
* 每个rabbitTemplate只能有一个confirm-callback和return-callback
*/
template.setConfirmCallback(msgSendConfirmCallBack());
//template.setReturnCallback(msgSendReturnCallback());
/**
* 使用return-callback时必须设置mandatory为true,或者在配置中设置mandatory-expression的值为true,
* 可针对每次请求的消息去确定’mandatory’的boolean值,
* 只能在提供’return -callback’时使用,与mandatory互斥
*/
//  template.setMandatory(true);
return template;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
return new RabbitAdmin(connectionFactory);
}

/**
* 消息确认机制
* Confirms给客户端一种轻量级的方式,能够跟踪哪些消息被broker处理,
* 哪些可能因为broker宕掉或者网络失败的情况而重新发布。
* 确认并且保证消息被送达,提供了两种方式:发布确认和事务。(两者不可同时使用)
* 在channel为事务时,不可引入确认模式;同样channel为确认模式下,不可使用事务。
* @return
*/
@Bean
public MsgSendConfirmCallBack msgSendConfirmCallBack(){
return new MsgSendConfirmCallBack();
}

}

交换机配置

ExchangeConfig .java,我默认配置了两个交换机

package com.hegoo.device.config;

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

/**
* @author zhangyr
* @date 2020/5/13 14:29
* @description 消息交换机配置  可以配置多个
*/

@Configuration
public class ExchangeConfig {
/**
*   1.定义direct exchange,绑定queueTest
*   2.durable="true" rabbitmq重启的时候不需要创建新的交换机
*   3.direct交换器相对来说比较简单,匹配规则为:如果路由键匹配,消息就被投送到相关的队列
*     fanout交换器中没有路由键的概念,他会把消息发送到所有绑定在此交换器上面的队列中。
*     topic交换器你采用模糊匹配路由键的原则进行转发消息到队列中
*   key: queue在该direct-exchange中的key值,当消息发送给direct-exchange中指定key为设置值时,
*   消息将会转发给queue参数指定的消息队列
*/
@Bean
public DirectExchange directDataExchange(){
DirectExchange directExchange = new DirectExchange(RabbitMqConfig.EXCHANGE1,true,false);
return directExchange;
}
@Bean
public DirectExchange directStatusExchange(){
DirectExchange directExchange = new DirectExchange(RabbitMqConfig.EXCHANGE2,true,false);
return directExchange;
}
}

生产者

因为我的业务需求需要动态的添加队列,所以我这里把添加队列的方法写出来给大家参考

/**
* 创建队列和绑定交换机
* @param queceName 队列名
* @param key 绑定规则
*/
private void createDataQuece(String queceName, String key) {

Queue dataQueue = new Queue(queceName, true, false, false);
rabbitAdmin.declareQueue(dataQueue);
Binding bindingData = BindingBuilder.bind(dataQueue).to(exchangeConfig.directDataExchange()).with(key);
rabbitAdmin.declareBinding(bindingData);
createListener(productKey, deviceKey, dataQueceName);
}

发送消息

/**
* rabittMQ发送消息
*
* @param uuid
* @param message    消息
* @param routingKey
*/
public void sendData(String uuid, Object message, String routingKey) {
CorrelationData correlationId = new CorrelationData(uuid);
rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE1, routingKey,
message, correlationId);
}

消费者

springboot注解配置消费者,生产者也可以用这种注解的方式生成

package com.hegoo.data.rabbitmq.mqlistener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
* @author zhangyr
* @date 2020/5/13 14:45
* @description
*/
@Slf4j
@Component
public class FirstListener {

@RabbitListener(queues = {"status/:productName/:deviceName"}, containerFactory = "rabbitListenerContainerFactory")
public void handleMessage(String message) throws Exception {
// 处理消息
log.info("FirstConsumer {} handleMessage :"+message);
Thread.sleep(1000);
}
}
标签: