一、pom.xml和配置文件(使用之前安装RabbitMQ服务--省略)
<!-- 整合搭建rabbitMq --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
server: port: 9010 spring: application: name: springCloud-rabbitMq eureka: instance: hostname: localhost client: register-with-eureka: true fetch-registry: false service-url: defaultZone: http://localhost:9001/eureka/
spring: rabbitmq: host: localhost port: 5672 username: guest password: guest
二、配置config
package rabbitMq.config; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 初始化配置加载队列消息 */ @Configuration public class RabbitConfig { @Bean(name="hello1") public Queue helloQueue1() { return new Queue("hello1"); } /**实现一对一、一对多功能 @Bean public TopicExchange exchange(){ return new TopicExchange("exchange"); } @Bean Binding bindingExchangeMessage(@Qualifier("hello1") Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with("topic.hello1"); } @Bean Binding bindingExchangeMessages(@Qualifier("hello2") Queue queueMessages, TopicExchange exchange) { return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#"); }**/ }
三、消息发送端
package rabbitMq.sender; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import rabbitMq.model.User; import java.util.Date; /** * 发送消息 */ @Component public class Sender { @Autowired private AmqpTemplate rabbitTemplate; /** * string类型的字符串 */ public void send1() { String context = "发送消息测试1"; this.rabbitTemplate.convertAndSend("hello1", context); } }
四、消息接收端
package rabbitMq.receive; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; /** * 接受消息 */ @Component @RabbitListener(queues = "hello1") public class Receiver1 { @RabbitHandler public void process(String hello) { System.out.println("接受消息1对象内容 : " + hello); } }
五、controller层处理业务响应结果
package rabbitMq.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import rabbitMq.sender.Sender; @RestController public class RabbitController { @Autowired private Sender sender; @RequestMapping("/test1") public void test1(){ sender.send1(); } }
六、启动服务调用接口响应控制台输出--省略