springcloud-eureka cluster - integrating Rabbit message middleware

1. Configure the rabbitmq server



2. Write the message sender

Add dependency pom.xml

<!-- 消息驱动 -->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

Modify configuration application.yml

server:
  port: 8088

spring:
  application:
    name: tms-send
  rabbitmq:
    host: 192.168.1.109
    port: 5672
    username: rabbit-username
    password: rabbit-password

Startup class TmsSendApplication.java

@SpringBootApplication@EnableEurekaClient@EnableBinding(RabbitSendService.class)
public class TmsSendApplication {
   public static void main(String[] args) {


      SpringApplication.run(TmsSendApplication.class, args);
   }
}

Write the send interface

public interface RabbitSendService {
    @Output(value = "myInput")
    SubscribableChannel sendMsg() throws Exception;
}

write 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





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324700672&siteId=291194637