引入依赖jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
引入配置
@Configuration
public class RabbitConfig {
final static String message = "sanguo.message";
final static String message2 = "sanguo.message2";
final static String TOPIC_EXCHANGE ="exchange";
@Bean
public Queue queue1() {
return new Queue(message);
}
@Bean
public Queue queue2() {
return new Queue(message2);
}
@Bean
TopicExchange exchange() {
return new TopicExchange(TOPIC_EXCHANGE);
}
@Bean
Binding bindingExchangeMessages(Queue queue1, TopicExchange exchange) {
System.out.println(queue1.getName());
return BindingBuilder.bind(queue1).to(exchange).with("sanguo.#");
}
@Bean
Binding bindingExchangeMessage(Queue queue2, TopicExchange exchange) {
System.out.println(queue2.getName());
return BindingBuilder.bind(queue2).to(exchange).with("sanguo.message");
}
}
这里做个笔记,RabbitMQ是通过交换机给queue发消息,但是中间还会通过RoutingKey进行过滤,BindingBuilder.bind(queue2).to(exchange).with(“sanguo.message”) 这句话的意思就是,通过交换机exchange发送的消息,满足RoutingKey条件的(sanguo.message)会被转发到queue2里面
下面是具体的消息发送
@Component
public class HelloSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = "hello " + LocalDateTime.now();
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("exchange","sanguo.aaa", context);
//交换机,key,具体内容
}
}
接收端–记得也要引入上面的依赖
@Component
@RabbitListener(queues = "sanguo.message")
public class HelloReceiver {
//这里接收类型可以指定一个对象
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver : " + hello);
}
}
配置文件(接收端和发送端都需要)
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest