direct并不能满足我们的业务需求,因为direct只能绑定一个固定的消息类型,但是topic就可以使用通配符,绑定一类的消息类型
配置
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TopicConfig {
final static String MESSAGE = "topic.message";
final static String MESSAGES = "topic.messages";
@Bean
public Queue queueMessage() {
return new Queue(MESSAGE);
}
@Bean
public Queue queueMessages() {
return new Queue(MESSAGES);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("exchange");
}
/**
* 将队列topic.message与exchange绑定,binding_key为topic.message,就是完全匹配
* @param queueMessage
* @param exchange
* @return
*/
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
}
/**
* 将队列topic.messages与exchange绑定,binding_key为topic.#,模糊匹配
* @param queueMessages
* @param exchange
* @return
*/
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
}
}
生产者
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TopicExchangeProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send() {
rabbitTemplate.convertAndSend("exchange", "topic.message", "topic.message");
rabbitTemplate.convertAndSend("exchange", "topic.messages", "topic.messages");
}
}
消费者
/**
* 消费者messages
*/
@Component
@RabbitListener(queues = "topic.messages")
public class MessagesCustomer {
@RabbitHandler
public void process(String msg){
System.out.println("topicexchange messages 消费者 : " +msg);
}
}
/**
* 消费者message
*/
@Component
@RabbitListener(queues = "topic.message")
public class MessageCustomer {
@RabbitHandler
public void process(String msg){
System.out.println("topicexchange message 消费者 : " +msg);
}
}
测试类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TopicController {
@Autowired
private TopicExchangeProducer topicExchangeProducer;
@RequestMapping("/topicexchange")
public String topicExchange(){
topicExchangeProducer.send();
return "ok";
}
}