天天看點

springboot使用進階消息隊列RabbitMQ

使用工具idea,springboot版本2.0+,RabbitMQ我已經在自己的雲伺服器Linux上面安裝了,你們要測試的話,自己可以在本地安裝RabbitMQ

github位址是https://github.com/samdidemo/springboot-rabbitMQ.git

第一步,建立新工程

springboot使用進階消息隊列RabbitMQ

第二步,引進相應的依賴

springboot使用進階消息隊列RabbitMQ

然後,在application.properties中添加配置,伺服器位址,就是你安裝RabbitMQ的ip位址,如果你是安裝在本地,那麼你直接寫localhost就行,使用者名和密碼預設是guest

springboot使用進階消息隊列RabbitMQ

在主類中添加@EnableRabbit注解,開啟RabbitMQ

springboot使用進階消息隊列RabbitMQ

建立一個類,其中建立一個方法,比如在這個方法開頭添加注解@RabbitListener(queues = "lin"),它便會監聽消息隊列lin,一旦裡面有消息,便會進行接收

public class rabbitService {
    @RabbitListener(queues = "lin")
    public void recieve(Map<String, Object> map){
        System.out.println(map.toString());
    }
}
           

我們可以在測試類中自動注入RabbitTemplate template; 然後使用template.convertAndSend("linyongbin","lin",map)發送消息到隊列中,測試是否接收到了消息

其中“linyongbin”是交換機的名字,“lin”是路由鍵,map是要傳送的東西

@Autowired
    RabbitTemplate template;
    @Test
    public void contextLoads() {
        Map<String,Object> map=new HashMap<>();
        map.put("msg","林陽光發送消息");
        map.put("name","linyongbin");
        template.convertAndSend("linyongbin","lin",map);
    }
           

繼續閱讀