1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、发送消息
@Autowired
private AmqpTemplate amqpTemplate;
private void sendMessage(Long id, String type) {
// 发送消息
try {
amqpTemplate.convertAndSend("item." + type, id);
} catch (Exception e) {
log.error("消息发送异常");
}
}
3、监听消息
@Component
public class GoodsListener {
/**
* 处理insert和update的消息
*
* @param id
* @throws Exception
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "renren.create.index.queue", durable = "true"),
exchange = @Exchange(
value = "renren.item.exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC),
key = {"item.insert", "item.update"}))
public void listenCreate(Long id) throws Exception {
if (id == null) {
return;
}
System.out.println(id);
}
/**
* 处理delete的消息
*
* @param id
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "renren.delete.index.queue", durable = "true"),
exchange = @Exchange(
value = "renren.item.exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC),
key = "item.delete"))
public void listenDelete(Long id) {
if (id == null) {
return;
}
System.out.println(id);
}
}