加入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
配置文件
spring:
application:
name: rabbitmq-springboot
rabbitmq:
host: 127.0.0.1
port: 5672
username: ems
password: 123
virtual-host: /ems
生产者:
@SpringBootTest class RabbitmqSpringbootApplicationTests { @Autowired private RabbitTemplate rabbitTemplate; //动态路由 订阅模式 topic @Test public void testTopic() { rabbitTemplate.convertAndSend("topics","order.save","user.save路由消息"); }; //routing路由模式 direct @Test public void testDirect() { rabbitTemplate.convertAndSend("logs_directs","info","发送info的key路由"); }; //fanout广播 @Test void testfanout() { rabbitTemplate.convertAndSend("logs","","Fanout的模型发送的消息"); }; @Test void testwork() { for (int i = 0; i < 10; i++) { rabbitTemplate.convertAndSend("work","work模型"); } }; @Test void testHello() { rabbitTemplate.convertAndSend("hello","hello world"); } }
消费者1
@Component //监听那个队列 //@Queue队列默认设置就是最常用的 持久化 非独占 不是自动删除队列 @RabbitListener(queuesToDeclare = @Queue("hello")) public class HelloCustomer { //当我们从hello队列中取出消息时的回调方法 @RabbitHandler public void receivel(String message) { System.out.println("message="+message); }; }
消费者2
@Component public class WorkCustomer { @RabbitListener(queuesToDeclare = @Queue("work")) public void receivel1(String message) { System.out.println("message1"+message); }; @RabbitListener(queuesToDeclare = @Queue("work")) public void receivel2(String message) { System.out.println("message2"+message); }; }
消费者3
@Component public class FanoutCustomer { @RabbitListener(bindings = { @QueueBinding( value = @Queue,//不指定值就是创建临时队列 exchange = @Exchange(value = "logs",type = "fanout")//绑定交换机 ) }) public void receivel1(String message) { System.out.println("message-1"+message); }; @RabbitListener(bindings = { @QueueBinding( value = @Queue, exchange = @Exchange(value = "logs",type = "fanout") ) }) public void receivel2(String message) { System.out.println("message-2"+message); }; }
消费者4
@Component public class DirectCustomer { @RabbitListener(bindings = @QueueBinding( value = @Queue, exchange = @Exchange(value = "logs_directs",type = "direct"), key = {"info","error","warning"} ) ) public void receivel1(String message) { System.out.println("message-1"+message); }; @RabbitListener(bindings = @QueueBinding( value = @Queue, exchange = @Exchange(value = "logs_directs",type = "direct"), key = {"error"} )) public void receivel2(String message) { System.out.println("message-2"+message); }; }
消费者5
@Component public class TopicCoustomer { @RabbitListener(bindings =@QueueBinding( value = @Queue, exchange = @Exchange(value = "topics",type = "topic"), key = {"user.*"} )) public void receivel1(String message) { System.out.println("message-1"+message); }; @RabbitListener(bindings = @QueueBinding( value = @Queue, exchange = @Exchange(value = "topics",type = "topic"), key = {"order.#","user.#"} )) public void receivel2(String message) { System.out.println("message-2"+message); }; }