首先在springBoot中引入RabbitMQ的依赖
org.springframework.boot
spring-boot-starter-amqp
配置:
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
direct:
acknowledge-mode: manual
publisher-confirm: true #开启发送确认
publisher-returns: true #开启发送失败
编写配置类:
@Configuration
public class RabbitConfig {
/*
* 制定交换机Exchange:DirectExchange 根据路由键完全匹配进行路由消息队列
* 直连交换机 精确匹配
* */
@Bean
public DirectExchange directExchange(){
//创建了一个直连的交换机 名字是change1 他会在rabbitmq上创建一个交换机
return new DirectExchange("change1");
}
/*
创建一个队列 用来存放change1路由过来的消息
* */
@Bean
public Queue queue1(){
//队列名
return new Queue("queue1");
}
/*
* 建立关系 交换机和队列绑定起来
* */
@Bean
public Binding bingdingDirectEschange(Queue queue1, DirectExchange directExchange){
return BindingBuilder.bind(queue1).to(directExchange).with("routingKey10");
}
}
生产者:
消费者:
@Component
@RabbitListener(queues = “queue1”)
public class MessageReceiver {
@RabbitHandler
public void process(String hello, Channel channel, Message message){
try {
Thread.sleep(1000);
System.out.println("休眠1秒");
System.out.println("receiver success>>>"+hello);
} catch (Exception e){
e.printStackTrace();
}
}
}