SpringBoot項目嵌入RocketMQ的實現(xiàn)示例
在Spring Boot中嵌入RocketMQ可以通過添加相應(yīng)的依賴來完成。
首先需要在pom.xml文件中引入spring-boot-starter-amqp依賴:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
然后,在application.properties或者application.yml配置文件中設(shè)置RocketMQ連接信息:
# RocketMQ服務(wù)器地址 rocketmq.name-server=127.0.0.1:9876 # 生產(chǎn)者分組 rocketmq.producer.group=my-group
最后,創(chuàng)建消息發(fā)送者(Producer)和消息接收者(Consumer)類,并使用@Autowired注解將其自動裝載到Spring容器中。示例如下:
創(chuàng)建消息發(fā)送者類:
import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ProducerController { @Autowired private RocketMQTemplate rocketMQTemplate; @GetMapping("/send") public String send(String message) { rocketMQTemplate.convertAndSend("test-topic", message); return "Message: '" + message + "' sent."; } }
創(chuàng)建消息接收者類:
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.stereotype.Service; @Service @RocketMQMessageListener(topic = "test-topic", consumerGroup = "my-consumer_test-topic") public class ConsumerService implements RocketMQListener<String> { @Override public void onMessage(String message) { System.out.printf("------- StringConsumer received: %s \n", message); } }
當調(diào)用/send
接口時,會向"myQueue"隊列發(fā)送消息;
而MessageReceiver
則會監(jiān)聽該隊列,并處理接收到的消息。
查看控制臺的輸出來驗證消息消費者是否可以正常接收消息
到此這篇關(guān)于SpringBoot項目嵌入RocketMQ的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot嵌入RocketMQ內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Myeclipse鏈接Oracle等數(shù)據(jù)庫時lo exception: The Network Adapter coul
今天小編就為大家分享一篇關(guān)于Myeclipse鏈接Oracle等數(shù)據(jù)庫時lo exception: The Network Adapter could not establish the connection,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼
這篇文章主要介紹了Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01