RabbitMq(三):SpringBoot引入RabbitMq

1. springBoot項目下引入amqp starter

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

amqp-starter 會引入如下jar包

[INFO] \- org.springframework.boot:spring-boot-starter-amqp:jar:2.1.5.RELEASE:compile
[INFO]    +- org.springframework:spring-messaging:jar:5.1.7.RELEASE:compile
[INFO]    \- org.springframework.amqp:spring-rabbit:jar:2.1.6.RELEASE:compile
[INFO]       +- org.springframework.amqp:spring-amqp:jar:2.1.6.RELEASE:compile
[INFO]       |  \- org.springframework.retry:spring-retry:jar:1.2.4.RELEASE:compile
[INFO]       +- com.rabbitmq:amqp-client:jar:5.4.3:compile
[INFO]       |  \- org.slf4j:slf4j-api:jar:1.7.26:compile
[INFO]       \- org.springframework:spring-tx:jar:5.1.7.RELEASE:compile

2. springBoot 配置文件下配置rabbitMQ屬性

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

3. 創(chuàng)建Queue并注入到spring容器中

@Configuration
public class QueueConfig {
    @Bean
    public Queue queue() {
        return new Queue("test_queue");
    }
}

4. Sender 發(fā)送數(shù)據(jù)到Queue

@Component
public class Sender {
    @Autowired
    private AmqpTemplate template;
    public void send(String message) {
        template.convertAndSend("test_queue",message);
    }
}

其中AmqpTemplate是SpringBoot生成的默認(rèn)實(shí)現(xiàn),在代碼里面可以直接引入使用。

5. Receiver 消費(fèi)Queue中的數(shù)據(jù)

@Component
@RabbitListener(queues = "test_queue")
public class Receiver {
    Logger logger = LoggerFactory.getLogger(Receiver.class.getName());
    @RabbitHandler
    public void process(String message) {
        logger.info(message);
    }
}

添加Queue的listener,并對收到的消息進(jìn)行處理。注意,receiver要注入到容器中(@Component)才能對消息進(jìn)行監(jiān)聽。

上面采用Direct的方式來使用queue。接下來使用Topic、Fanout...

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容