【RabbitMQ】springboot用例(十)
Topic模式
生产者
@Configuration
public class RabbitMqTopicConfiguration {
// 1、声明 Topic 交换机
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(Constants.TOPIC_EXCHANGE_NAME, true, false);
}
// 2、声明队列
@Bean(Constants.QUEUE_TOPIC_QUEUE3)
public Queue queue3() {
return new Queue(Constants.QUEUE_TOPIC_QUEUE3);
}
@Bean(Constants.QUEUE_TOPIC_QUEUE4)
public Queue queue4() {
return new Queue(Constants.QUEUE_TOPIC_QUEUE4);
}
@Bean(Constants.QUEUE_TOPIC_QUEUE5)
public Queue queue5() {
return new Queue(Constants.QUEUE_TOPIC_QUEUE5);
}
// 3、绑定队列
@Bean("queue3Binding")
public Binding queue1Binding() {
return BindingBuilder.bind(queue3()).to(topicExchange()).with("#.orange.*");
}
@Bean("queue4Binding")
public Binding queue4Binding() {
return BindingBuilder.bind(queue4()).to(topicExchange()).with("lazy.#");
}
@Bean("queue5Binding")
public Binding queue5Binding() {
return BindingBuilder.bind(queue5()).to(topicExchange()).with("*.*.rabbit");
}
}
@Service
public class TopicSendMsgService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMsg(String msg, String routingKey) {
rabbitTemplate.convertAndSend(Constants.TOPIC_EXCHANGE_NAME, routingKey, msg);
}
}
消费
@Component
@RabbitListener(queues = Constants.QUEUE_TOPIC_QUEUE3)
public class TopicQueue3MsgListener {
@RabbitHandler
public void receiveQueue3Msg(String message) {
try {
System.out.println("receiveQueue3Msg ====>>> " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
好学若饥,谦卑若愚