SpringBoot集成RabbitMQ

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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章