1.安装rabbitmq
2.创建springboot项目
3.配置连接
spring:
rabbitmq:
host: 10.80.56.207
port: 5672
username: test
password: test
virtual-host: /test
publisher-confirms: true
配置Config:Topic交换机、队列、绑定 路由规则等
@Configuration //配置类
ExchangeBuilder.topicExchange(exchangeName).durable(true).build(); //声明交换机
new Queue(queueName);//声明队列
BindingBuilder.bind(queue).to(exchange).with("ceshi.#"); //通过路由规则 绑定交换机和队列 路由规则必须是以“.”隔开的字符
@Configuration
public class RabbitMqConfig {
//交换机1
@Bean("exchange_test1")
public TopicExchange exchange1(){
return new TopicExchange("exchange_test1");
}
//队列1
@Bean("queue_test1")
public Queue queue1(){
return declare_Queue("queue_test1");
}
//绑定交换机1和队列1
@Bean
public Binding bind_Exchange_Queue(@Qualifier("exchange_test1") TopicExchange exchange,@Qualifier("queue_test1") Queue queue){
// return BindingBuilder.bind(queue).to(exchange).with("test#").noargs();
return BindingBuilder.bind(queue).to(exchange).with("ceshi.#");
}
}
生产者发送消息
@Autowired
private AmqpTemplate amqpTemplate;
public void sendTest1(){
//交换机名称
//路由key名称
//具体消息内容
amqpTemplate.convertAndSend("exchange_test1","ceshi.ceshi","this is my message:fuck you");
}
消费者消费消息
@RabbitListener(queues={"queue_test1"}) //监听“queue_test1”队列
public void reciveTest1(String msg){
System.out.println("接收消息内容==="+msg);
}
生产者和消费者可以放到2个项目中,启动生产者发送消息,关闭消费者,然后在mq的管理页面查看消息状态
然后再启动消费者 看消息状态