Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>配置文件
#默认配置可省略 spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.rabbitmq.virtual-host=/生产者
package com.example.rabbitmq; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController @SpringBootApplication public class RabbitmqApplication { public static void main(String[] args) { SpringApplication.run(RabbitmqApplication.class, args); } @Resource RabbitTemplate rabbitTemplate; @GetMapping("send") public String send() { //发送消息 rabbitTemplate.convertAndSend("MyExchange", "key", "msg"); rabbitTemplate.convertAndSend("MyExchange", "key", 123); return "1"; } }创建队列、交换器,绑定队列和交换器
package com.example.rabbitmq; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Config { //创建队列 @Bean Queue queue() { return new Queue("queue"); } //创建交换器 @Bean DirectExchange directExchange() { return new DirectExchange("MyExchange"); } //绑定队列和交换器 @Bean Binding binding() { return BindingBuilder.bind(queue()).to(directExchange()).with("key"); } }消费者
package com.example.rabbitmq; import org.springframework.amqp.rabbit.annotation.*; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = {"MyQueue","MyQueue1"}) //@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "MyQueue"), exchange = @Exchange(value = "MyExchange"), key = "key")}) //@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "MyQueue1"), exchange = @Exchange(value = "MyExchange1"), key = "key")}) public class Listener { @RabbitHandler public void test1(String message) { System.out.println(message); } @RabbitHandler public void test2(Integer message) { System.out.println(message); } }@RabbitListener
可单独用于方法上;
@RabbitListener
用于类上时必须在目标方法上使用 @RabbitHandler,按message类型调用对应方法;
@RabbitListener(bindings = {@QueueBinding(value = @Queue(value = “MyQueue”), exchange = @Exchange(value = “MyExchange”), key = “key”)})
绑定队列和交换器,不存在时自动创建,同一类或方法上可使用多个 @RabbitListener