1:新建amqp-demo工程并添加依赖
<dependencies> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2:新建producer模块
(1)application.properties
server.port=8081 spring.rabbitmq.addresses=192.168.100.13:5672 spring.rabbitmq.connection-timeout=15000 spring.rabbitmq.username=admin spring.rabbitmq.password=admin
(2)RabbitMQConfig.java
@Configuration public class RabbitMQConfig { public static final String MY_TOPIC_EXCHANGE = "my_topic_exchange"; public static final String MY_QUEUE = "my_queue"; @Bean("myTopicExchange") public Exchange myTopicExchange(){ return ExchangeBuilder.topicExchange(MY_TOPIC_EXCHANGE).durable(true).build(); } @Bean("myQueue") public Queue myQueue(){ return QueueBuilder.durable(MY_QUEUE).build(); } @Bean public Binding itemQueueExchange(@Qualifier("myQueue") Queue queue, @Qualifier("myTopicExchange") Exchange exchange){ return BindingBuilder.bind(queue).to(exchange).with("my.#").noargs(); } }
(3)RabbitSender.java
@Component public class RabbitSender { @Autowired private RabbitTemplate rabbitTemplate; public void sendMsg(String key, Object msg){ rabbitTemplate.convertAndSend(RabbitMQConfig.MY_TOPIC_EXCHANGE, key, msg); } }
(4)SenderController.java
@RestController @RequestMapping( value = "/message", produces = "application/json;charset=utf-8", headers = "Accept=application/json" ) public class SenderController { @Autowired private RabbitSender rabbitSender; @PostMapping("/sender") public Map<String,Object> sender(@RequestBody Map<String,Object> params){ Map<String,Object> result = new HashMap<>(); int code = 0; String msg = "消息发送成功"; rabbitSender.sendMsg("my.queue", params); result.put("code", code); result.put("msg", msg); return result; } }
3:新建consumer模块
(1)application.properties
server.port=8083 spring.rabbitmq.addresses=192.168.100.13:5672 spring.rabbitmq.connection-timeout=15000 spring.rabbitmq.username=admin spring.rabbitmq.password=admin spring.rabbitmq.listener.concurrency=10 spring.rabbitmq.listener.max-concurrency=20 spring.rabbitmq.listener.prefetch=5
(2)RabbitReceiver.java
@Component public class RabbitReceiver { @RabbitListener(queuesToDeclare = @Queue("my_queue")) public void onMessage(Map<String,Object> msg){ System.out.println("收到消息:"+msg); } }