之前写了两篇,感觉对于入门的小伙伴,不太友好。
所以这次,就写一个简单的。
一,架包
implementation("org.springframework.boot:spring-boot-starter-amqp:2.5.4")
二,配置config
spring.rabbitmq.host = 127.0.0.1 spring.rabbitmq.port = 5672 spring.rabbitmq.username = guest spring.rabbitmq.password = guest
三,配置queuq-exchange--topic
package com.tenyears.webAD.config.mq; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; 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.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.amqp.RabbitProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description : * @auther Tyler * @date 2021/8/25 */ @Configuration @EnableApolloConfig public class RabbitMQConfig extends MqBaseConfig { public final static String my_queue= "my_queue"; public final static String my_topic = "my_topic"; //声明 queue @Bean public Queue MY_QUEUE() { return new Queue(my_queue,true); } //声明 topic @Bean TopicExchange exchange() { return new TopicExchange(my_topic); } // 绑定 queue , exchange, routing_key @Bean Binding bindingExchangeMessage() { return BindingBuilder.bind(AD_SCHEDULE_QUEUE()).to(exchange()).with(my_queue); } }
主要缩明一下 routing_key 作为路由键,
假设 改成 my_queue#,
则可以匹配多个 queue,比如: my_queue1 , my_queue2............
四,生产者
@GetMapping(value = "test1") public String test1(@RequestBody String str) { //参数1:exchange //参数2:routeKey //参数3:消息 rabbitTemplate.convertSendAndReceive(RabbitMQConfig.my_topic,RabbitMQConfig.my_queue , "123"); return "已发送"; }
五,消费者
@Component @Lazy(false) @RabbitListener(queues = RabbitMQConfig.my_queue) public class AdScheduleExtendHandler { @RabbitHandler public void test(String a) { System.out.println("=================="+a); } }