mq上有好多個消息,若是兩個系統共同使用一個mq,怎麼區分mq裏的消息是這兩個系統中哪個的呢,mq提供了一種方法---消息列隊java
首先在mq上建立一個消息列隊,名字是惟一的,而後系統根據消息列隊的名字----向消息列隊中存數據和取數據web
springboot集成ribbitMQ通常要作的事情----連接mq---建立一個標識(建立消息列隊)----像消息列隊中添加值-------從消息列隊中取值spring
springboot集成rabbitmq要作的事情apache
1:引入jarspringboot
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>app
2:在application.properties配置 ip、端口、用戶名和密碼spring-boot
spring.application.name=spirng-boot-rabbitmq
spring.rabbitmq.host=192.168.146.134
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123工具
3:建立一個RabbitConfig類 ,目的spring初始化時候在mq上建立一個消息列隊測試
package com.blueskystarts.module.mq;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
@Bean
public Queue Queue() {
return new Queue("helloMQ");//會在mq上建立一個名爲helloMQ的消息列隊
}
}spa
4:建立一個消息接收類----只要mq對應的消息列隊中有消息就獲取消息
package com.blueskystarts.module.mq;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "helloMQ")
public class HelloReceiver {
@RabbitHandler
public void process(String message) {
System.out.println("從helloMQ獲取的消息message: ==========================="+message);
}
}
上面使用的是springboot自帶的獲取mq的工具,只要加上對應的註解,就能獲取到想要的消息列隊的消息
5:寫個接口發個消息測試下----springboot有個rabbitTemplate類,這個類裏有方法能夠向mq的消息列隊中添加消息
package com.blueskystarts.module.mq.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testmq")
public class SendMQController {
@Autowired
private AmqpTemplate rabbitTemplate;
//http://127.0.0.1:8080/testmq/sendmessage
@GetMapping(value = "/sendmessage")
public String sendMessage(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String test = "當前時間:"+dateFormat.format(new Date());
rabbitTemplate.convertAndSend("helloMQ", test);
return "消息已經發送到helloMQ消息列隊中";
}
}
6:在頁面上執行接口:http://127.0.0.1:8080/testmq/sendmessage
查看eclipce控制檯