赞
踩
配置好rabbitmq服务器
编写消息发送者
添加依赖pom.xml
- <!-- 消息驱动 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
- </dependency>
修改配置application.yml
- server:
- port: 8088
-
- spring:
- application:
- name: tms-send
- rabbitmq:
- host: 192.168.1.109
- port: 5672
- username: rabbit-username
- password: rabbit-password
启动类 TmsSendApplication.java
- @SpringBootApplication
- @EnableEurekaClient
- @EnableBinding(RabbitSendService.class)
- public class TmsSendApplication {
- public static void main(String[] args) {
- SpringApplication.run(TmsSendApplication.class, args);
- }
- }
编写发送接口
- public interface RabbitSendService {
- @Output(value = "myInput")
- SubscribableChannel sendMsg() throws Exception;
- }
编写controller
- @RestController
- public class TestController {
-
- @Autowired
- private RabbitSendService rabbitService;
-
- @GetMapping(value = "/sendMsg")
- public String sendMsg() throws Exception {
- Message message = MessageBuilder.withPayload("Hello World".getBytes()).build();
- rabbitService.sendMsg().send(message);
- return "success";
- }
- }
三、编写消息接受者
添加依赖pom.xml
- <!-- 消息驱动 -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
- </dependency>
修改配置application.yml
- server:
- port: 8088
-
- spring:
- application:
- name: tms-send
- rabbitmq:
- host: 192.168.1.109
- port: 5672
- username: rabbit-username
- password: rabbit-password
启动类 TmsSendApplication.java
- @SpringBootApplication
- @EnableEurekaClient
- @EnableBinding(RabbitReceiveService.class)
- public class TmsReceiveApplication {
- public static void main(String[] args) {
- SpringApplication.run(TmsReceiveApplication.class, args);
- }
- }
编写消息监听
- @Component
- public class RabbitReceiveListener {
- @StreamListener(value = "myInput")
- public void onReceive(byte[] msg){
- System.out.println(new String(msg));
- }
- }
编写消息接口
- public interface RabbitReceiveService {
- @Input(value = "myInput")
- SubscribableChannel inputMsg() throws Exception;
- }
四、启动eureka注册中心,启动消息发送者与消息接收者
访问接口 http://127.0.0.1:8088/sendMsg
消息接收者的的监听器获取到的消息
Hello World
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。