一,springboot整合rabbitMQ可以简单配置就可以投入使用,springboot会自动装载配置
spring.rabbitmq.host=10.10.1.110
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
#确保消息在未被队列接收时返回
spring.rabbitmq.publisher-returns=true
#确保消息成功发送到交换器
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.virtual-host=/
创建队列,交换机,绑定交换机
@Slf4j
@Configuration
public class RabbitMQConfiguration {
/**
* 预警消息队列
*/
public final static String DEVICE_ALARM_QUEUE = "Device_Alarm";
@Bean
public Queue deviceAlarmQueue() {
return new Queue(DEVICE_ALARM_QUEUE);
}
/**
* 终端推送Exchange
*/
public final static String TERMINAL_EXCHANGE = "Terminal";
@Bean
public TopicExchange terminalExchange() {
return new TopicExchange(TERMINAL_EXCHANGE);
}
@Bean
public Binding bindingDeviceAlarmExchange() {
Binding binding = BindingBuilder
.bind(deviceAlarmQueue())
.to(terminalExchange())
.with("Terminal.Device_Alarm");
log.info("-----> TopicExchange:{} Queue:{} routeKey:{} <-----", TERMINAL_EXCHANGE, DEVICE_ALARM_QUEUE, "Terminal.device_alarm");
return binding;
}
}
监听消息:
@Slf4j
@Configuration
public class RabbitMQConsumerImpl {
/**
* 接受设备告警消息
*
* @param message
* @param channel
* @throws Exception
*/
@RabbitHandler
@RabbitListener(queues = RabbitMQConfiguration.DEVICE_ALARM_QUEUE)
public void receiveDeviceAlarm(Message message, Channel channel) throws Exception {
MsgHandleStrategy msgHandleStrategy = strategyFactory.doGetHandler(TaskConstant.ALARM_LOG_TASK);
msgHandleStrategy.terminalToPlatform(new String(message.getBody()));
String time = LocalDateTime.now().format(DTF);
System.out.printf("Queue[%s] Time[%s] %s%n", RabbitMQConfiguration.DEVICE_ALARM_QUEUE, time, message);
}
}
发送消息:
@Slf4j
@Component
public class RabbitMQProducerImpl {
@Autowired
private AmqpTemplate rabbitTemplate;
public void synchronizationDeviceDoor(String message) {
rabbitTemplate.convertAndSend(RabbitMQConfiguration.TERMINAL_FANOUT_EXCHANGE, "", message);
log.info("门控消息:" + message);
}
}
二,开启消息手动确认功能,确保消息消费成功,业务流程完整
增加配置:
#消息手动确认模式
spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.listener.simple.concurrency=2
spring.rabbitmq.listener.simple.max-concurrency=10
spring.rabbitmq.listener.simple.prefetch=2
消费时手动确认消息:
/**
* 抓拍消息
*
* @param message
* @param channel
* @throws Exception
*/
@RabbitHandler
@RabbitListener(queues = RabbitMQConfiguration.SNAP_DATA_QUEUE)
public void sysSnapData(Message message, Channel channel) throws Exception {
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
String value = new String(message.getBody());
MsgHandleStrategy sysHeartBeat = strategyFactory.doGetHandler(TaskConstant.SYS_SNAP_DATA_TASK);
sysHeartBeat.terminalToPlatform(value);
} catch (Exception e) {
log.error("消息重试:{}", e);
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
以上就是一个简单的rabbitMQ整合,使用