- 引入项目依赖
org.springframework.boot spring-boot-starter-amqp
注:需要新建项目
- 配置环境
spring: application: name: rabbitmq-springboot rabbitmq: host: 192.168.74.153 port: 5672 username: sofia password: sofia virtual-host: /sofia
注:需要提前安装rabbitMQ,需要配置虚拟主机,本文配置虚拟主机名称为:sofia,安装及使用见
https://editor.csdn.net/md/?articleId=122265369
springboot为rabbitMQ提供了一个rabbittemplate对象,可以直接使用
生产者:
@SpringBootTest(classes = RabbitmqSpringbootApplication.class) @RunWith(SpringRunner.class) public class TestRabbitMQ { @Autowired private RabbitTemplate rabbitTemplate; //hello world模式 @Test public void testHelloWorld(){ rabbitTemplate.convertAndSend("hello","helloworld!"); } }
消费者:
@Component @RabbitListener(queuesToDeclare = @Queue("hello")) public class helloConsumer { @RabbitHandler public void reciver(String message){ System.out.println("message = " + message); } }
queuesToDeclare :若队列不存在,则创建一个
还可设置队列的其他属性:
@RabbitListener(queuesToDeclare = @Queue(value = "hello", durable = "true", autoDelete = "false"))
durable :是否持久化、autoDelete :是否自动删除
2. springboot 不同模式API
- fanout模式
生产者测试代码:
//fanout模式 @Test public void testFanout(){ rabbitTemplate.convertAndSend("fanlutEx","","fanout模式下发送的消息"); }
使用注解的方式将消费者队列绑定到交换机上(@QueueBinding),未声明队列的时候,rabbitMQ会使用临时队列,消息被发送给消费者后就自动删除:
消费者消费者测试代码:
@Component public class FanoutConsumer { //第一个消费者 @RabbitListener(bindings = @QueueBinding( value = @Queue, //使用临时队列 exchange = @Exchange(value = "fanlutEx", type = "fanout") )) public void fanoutReciver(String message){ System.out.println("message1 is "+message); } //第二个消费者 @RabbitListener(bindings = @QueueBinding( value = @Queue, //使用临时队列 exchange = @Exchange(value = "fanlutEx", type = "fanout") )) public void fanoutReciver2(String message){ System.out.println("message2 is "+message); } }
- routing模式
消费者代码:
@Component public class routingConsumer { //消费者1,路由键"key1","key2","key3" @RabbitListener(bindings = {@QueueBinding( value = @Queue, exchange = @Exchange(value = "RoutingEx", type = "direct"), key = {"key1","key2","key3"} )} ) public void routingReciver1(String message){ System.out.println("routing message1 is " + message); } //消费者2,路由键"key2","key3" @RabbitListener(bindings = {@QueueBinding( value = @Queue, exchange = @Exchange(value = "RoutingEx", type = "direct"), key = {"key2","key3"} )} ) public void routingReciver2(String message){ System.out.println("routing message2 is " + message); } }
生产者1,路由键key1
@Test public void testRouting1(){ rabbitTemplate.convertAndSend("RoutingEx","key1","Routing模式下发送的消息"); }
运行结果:
生产者2,路由键key2
@Test public void testRouting2(){ rabbitTemplate.convertAndSend("RoutingEx","key2","Routing模式下发送的消息"); }
运行结果:
这部分太简单了,不想写了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)