使用spring stream發(fā)送消息代碼實例
為什么使用spring stream ?
spring stream 是用來做消息隊列發(fā)送消息使用的。他隔離了各種消息隊列的區(qū)別,使用統(tǒng)一的編程模型來發(fā)送消息。
目前支持:
- rabbitmq
- kafka
- rocketmq
啟動rocketmq
rocketmq 支持windows
start mqnamesrv.cmd start mqbroker.cmd -n 127.0.0.1:9876 autoCreateTopicEnable=true
修改pom.xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rocketmq</artifactId>
</dependency>
增加發(fā)送接收J(rèn)AVA代碼
public interface InputOutput {
String MAIL_OUTPUT = "mailOutput";
String MAIL_INPUT = "mailInput";
String OUTPUT = "output";
String INPUT = "input";
@Output(OUTPUT)
MessageChannel output();
@Input(INPUT)
SubscribableChannel input();
@Output(MAIL_OUTPUT)
MessageChannel mailOutput();
@Input(MAIL_INPUT)
SubscribableChannel mailInput();
}
在應(yīng)用上增加注解
@EnableBinding({InputOutput.class})
增加yml配置
spring:
cloud:
stream:
rocketmq:
binder:
name-server: 127.0.0.1:9876
bindings:
output:
destination: bpmmessage
group: bpmmessage-group
input:
destination: bpmmessage
group: bpmmessage-group-consumer
mailOutput:
destination: mail
group: mail-group
mailInput:
destination: mail
group: mail-group-consumer
編寫代碼收發(fā)消息:
MessageModel messageModel=new MessageModel();
messageModel.setMsgType("mail");
messageModel.setContent("helloworld");
inputOutput.mailOutput().send( MessageBuilder.withPayload(
"mail"
).build());
inputOutput.output().send(
MessageBuilder.withPayload(
messageModel
).build()
);
這里發(fā)送的是兩類消息。
接收消息:
@Service
public class MessageListener {
@StreamListener(InputOutput.INPUT)
public void receive(MessageModel message) {
System.err.println(message);
System.err.println("ok");
}
@StreamListener(InputOutput.MAIL_INPUT)
public void receive(String message) {
System.err.println(message);
System.err.println("ok");
}
}
分別接收兩類消息
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Springboot疫苗接種行程管理系統(tǒng)的設(shè)計與實現(xiàn)
本文主要介紹了基于Springboot實現(xiàn)的疫苗接種行程管理系統(tǒng)的示例代碼,系統(tǒng)主要實現(xiàn)個人疫苗接種管理、行程管理、病史管理、風(fēng)險地區(qū)管理、核酸檢測報告結(jié)果上報、疫情新聞管理等功能,需要的可以參考一下2022-03-03
SpringBoot在 POM 中引入本地 JAR 包的方法
在開發(fā) Spring Boot 應(yīng)用程序時,您可能需要使用本地 JAR 包來添加自定義庫或功能,本文將介紹在 Spring Boot 項目的 POM 文件中如何引入本地 JAR 包,感興趣的朋友跟隨小編一起看看吧2023-08-08
MyBatis入門之增刪改查+數(shù)據(jù)庫字段和實體字段不一致問題處理方法
這篇文章主要介紹了MyBatis入門之增刪改查+數(shù)據(jù)庫字段和實體字段不一致問題處理方法,需要的朋友可以參考下2017-05-05
Spring Boot 整合 Apache Dubbo的示例代碼
Apache Dubbo是一款高性能、輕量級的開源 Java RPC 框架,這篇文章主要介紹了Spring Boot 整合 Apache Dubbo的方法,本文通過示例說明給大家講解的非常詳細(xì),需要的朋友可以參考下2021-07-07

