<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: localhost
port: 5672
这里注意Queue的导包的时候,导的包一定要是
amop.core下的包。
import org.springframework.amqp.core.Queue;
@Configuration
public class RabbitConfigDirect {
@Bean
public Queue directQueue(){
return new Queue("dirct_queue");
}
@Bean
public Queue directQueue2(){
return new Queue("dirct_queue2");
}
@Bean
public DirectExchange directExchange(){
return new DirectExchange("directExchange");
}
@Bean
public Binding bindingDirect(){
return BindingBuilder
.bind(directQueue())
.to(directExchange())
.with("direct");
}
@Bean
public Binding bindingDirect2(){
return BindingBuilder
.bind(directQueue2())
.to(directExchange())
.with("direct2");
}
}
@Service
public class MessageServiceRabbitmqDirectImpl implements MessageService {
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理队列 (rabbitmq direct),id:" + id);
amqpTemplate.convertAndSend("directExchange","direct",id);
}
}
消费消息——Listener
多个监听配上同一个消息队列,可以轮询消费消息
@Component
public class MessageListener {
@RabbitListener(queues = "dirct_queue")
public void receive(String id){
System.out.println("已完成短信发送业务(rabbitmq direct):id:" + id);
}
}
@Component
public class MessageListener2 {
@RabbitListener(queues = "dirct_queue")
public void receive(String id){
System.out.println("已完成短信发送业务(rabbitmq direct two):id:" + id);
}
}
代码几乎没区别,但是代码模式有区别
使用主题交换机可以实现直连交换机
绑定匹配规则发生了一些变化
@Service
public class MessageServiceRabbitmqTopicImpl implements MessageService {
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理队列 (rabbitmq topic),id:" + id);
amqpTemplate.convertAndSend("topicExchange","topic.*.id",id);
}
@Override
public String doMessage() {
return null;
}
}
交换机的代码几乎不用发生变化,只需要把直连交换机换成主题交换机
@Configuration
public class RabbitConfigTopic {
@Bean
public Queue topicQueue(){
return new Queue("topic_queue");
}
@Bean
public Queue topicQueue2(){
return new Queue("topic_queue2");
}
@Bean
public TopicExchange topicExchange(){
return new TopicExchange("topicExchange");
}
@Bean
public Binding bindingTopic(){
return BindingBuilder
.bind(topicQueue())
.to(topicExchange())
.with("topic.order.id");
}
@Bean
public Binding bindingTopic2(){
return BindingBuilder
.bind(topicQueue2())
.to(topicExchange())
.with("topic2");
}
}