xml配置
#rabbitmq配置
rabbitmq:
host: 106.55.168.234
port: 5672
virtual-host: / # 虚拟主机配置
publisher-returns: true
publisher-confirm-type: correlated #必须配置这个才会确认回调
listener:
direct:
acknowledge-mode: manual # # 手动ack消息,不使用默认的消费端确认
配置类
package com.kun.order.config;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author zhoukun 86547462@qq.com
* @version 1.0
* @date 2021/1/6 14:01
*/
@Configuration
public class MyMqConfig {
/**
* 容器中的Exchange,Queue,Binding会自动创建(前提rabbitmq没有的情况下)
*/
@Bean
public Queue OrderDelayQueue()
{
/**
* 官网:https://www.rabbitmq.com/extensions.html
*/
Map<String,Object> arguments=new HashMap<>();
arguments.put("x-message-ttl",60000);//队列生存时间
arguments.put("x-dead-letter-exchange", "order-event-exchange");//死信路由指定交换机
arguments.put("x-dead-letter-routing-key", "order.release.order");//指定路由键
//public Queue(String name, boolean durable(持久化), boolean exclusive(排它), boolean autoDelete(自动删除), @Nullable Map<String, Object> arguments)
return new Queue("order.delay.queue",true,false,false,arguments);
}
@Bean
public Queue OrderReleaseQueue()
{
return new Queue("order.release.queue",true,false,false);
}
@Bean
public Exchange OrderEventExchange(){
//String name, boolean durable(持久化), boolean autoDelete(自动删除), Map<String, Object>(配置参数) arguments
return new TopicExchange("order-event-exchange",true,false);
}
@Bean
public Binding OrderCreateOrderBinding()
{
//(String destination, Binding.DestinationType destinationType, String exchange, String routingKey, @Nullable Map<String, Object> arguments
return new Binding(
"order.delay.queue",
Binding.DestinationType.QUEUE,
"order-event-exchange",
"order.create.order",
null);
}
@Bean
public Binding OrderReleaseOrderBinding()
{
return new Binding(
"order.release.queue",
Binding.DestinationType.QUEUE,
"order-event-exchange",
"order.release.order",
null);
}
@RabbitListener(queues = "order.release.queue")
public void listener(String msg, Message message, Channel channel) throws IOException {
System.out.println("1分钟后监听到了{}"+msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
controller
@GetMapping("/createMsg")
public @ResponseBody String createMsg()
{
String msg=UUID.randomUUID().toString();
rabbitTemplate.convertAndSend("order-event-exchange",
"order.create.order",
msg,
new CorrelationData(UUID.randomUUID().toString()));
return "ok";
}