SpringBoot整合中間件RabbitMQ(五)

1.開啟注解

開啟基于RabbitMQ的注解

package com.invi;

import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//開啟基于注解的RabbitMQ
@EnableRabbit
@SpringBootApplication
public class Springboot02AmqpApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02AmqpApplication.class, args);
    }

}

2.監(jiān)聽程序

編寫監(jiān)聽服務(wù)

package com.invi.service;

import com.invi.bean.Book;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;


@Service
public class BookService {

    //數(shù)組的方式,可以監(jiān)聽多個隊列
    @RabbitListener(queues = "invi.news")
    public void receive(Book book) {
        System.out.println("invi.news隊列收到消息:" + book.toString());
    }
}

3.發(fā)送隊列消息

package com.invi;

import com.invi.bean.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot02AmqpApplicationTests {


    @Autowired
    RabbitTemplate rabbitTemplate;


    //發(fā)送-單播(點對點)
    @Test
    public void testExchangeDirect() {
 
        rabbitTemplate.convertAndSend("exchange.direct", "invi.news", new Book("《挪威森林》", "村上春樹"));
    }


}

運行測試:

2019-03-05 09:41:13.443  INFO 90011 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
invi.news隊列收到消息:Book{name='《挪威森林》', author='村上春樹'}
2019-03-05 09:41:13.474  INFO 90011 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-03-05 09:41:13.482  INFO 90011 --- [       Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already


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

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

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