三、Springboot學習5-整合RabbitMQ-2018-11-14
阿新 • • 發佈:2018-11-27
1. 出現原因:生產者大量產生資料時,消費者無法快速消費,需要一箇中間層,去緩衝這批資料
2. 訊息順序:訊息生產者-->交換器-->佇列-->消費者
3. 依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
4. 依賴環境ERlang安裝
官網: http://www.erlang.org/downloads
安裝好之後配置環境變數
cmd-->erl,出現版本代表成功安裝
5. 下載rabbitMQ:http://www.rabbitmq.com/install-windows.html
6. 啟動:
6.1 set ERLANG_HOME=xxxx
6.2 rabbitmq-server.bat(加入報錯就刪除C:\Users\kh\AppData\Roaming\RabbitMQ\db下所有檔案重新啟動)
6.3 在sbin目錄下, 執行rabbitmq-plugins.bat enable rabbitmq_management,安裝管理外掛
7. rabbit基本操作參考:https://www.cnblogs.com/ericli-ericli/p/5902270.html
8. 對rabbitmq進行配置
spring.application.name=spirng-boot-rabbitmq spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=15672 spring.rabbitmq.username=kanghu spring.rabbitmq.password=11111
9. 佇列配置
@Configuration public class RabbitConfig { @Bean public Queue Queue() { return new Queue("hello"); } }
生產者:
@Repository public class RabbitMQSend { @Autowired private AmqpTemplate rabbitTemplate; public void send() { String context = "hello " + new Date(); System.out.println("Sender : " + context); this.rabbitTemplate.convertAndSend("hello", context); } }
消費者:
@Component @RabbitListener(queues = "hello") public class RabbitMQReceiver { @RabbitHandler public void process(String hello) { System.out.println("Receiver : " + hello); } }
測試:
@RestController public class RabbitMQController { @Autowired RabbitMQSend rabbitMQSend; @RequestMapping("/rabbit") public void testRabbit() { rabbitMQSend.send(); } }
10. 啟動報錯:
原因:配置埠為5672,不是15672,15672是管理端的埠!