接上一篇:Springboot集成RabbitMq一-CSDN博客
1、搭建项目-消费者
与之前一样
2、创建配置类
package com.wym.rabbitmqconsumer.utils;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 DirectRabbitConfig {//队列 起名:TestDirectQueue@Beanpublic Queue TestDirectQueue() {return new Queue("TestDirectQueue",true);}//Direct交换机 起名:TestDirectExchange@BeanDirectExchange TestDirectExchange() {return new DirectExchange("TestDirectExchange");}//绑定 将队列和交换机绑定, 并设置用于匹配键:TestDirectRouting@BeanBinding bindingDirect() {return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting");}
}
3、创建消息接收接口
package com.wym.rabbitmqconsumer.controller;import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;import java.util.Map;@Component
@RabbitListener(queues = "TestDirectQueue")//监听的队列名称 TestDirectQueue
public class DirectReceiver {@RabbitHandlerpublic void process(Map testMessage) {System.out.println("DirectReceiver消费者收到消息 : " + testMessage.toString());}}
4、查看客户端
已经被消费
5、补充:导包、yml配置
<!--rabbitmq--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency>
server:port: 8082
spring:#给项目来个名字application:name: rabbitmq-provider#配置rabbitMq 服务器rabbitmq:host: 127.0.0.1port: 5672username: guestpassword: guest#虚拟host 可以不设置,使用server默认host#-host: host