Spring Cloud 學習紀要六:Stream

Spring Cloud Stream:消息驅動

  Spring Cloud Stream 是一個構建消息驅動微服務的框架,應用程序通過 input 或者 output 來與 Spring Cloud Stream 中 binder 交互,而 binder 負責與消息中間件交互。

開發環境 版本
IDEA 2018.2.6
JDK 1.8
Spring Boot 2.0.6
Spring Cloud Finchley.SR2
Docker 18.09.0
RabbitMQ 3.7.8-management

增加provider和consumer項目

添加依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

添加RabbitMQ配置

spring:
  rabbitmq:
    username: guest
    password: guest
    host: localhost
    port: 5672

普通RabbitMQ使用方式

provider生產消息

@RestController
@RequestMapping("/hello")
public class HelloController {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @GetMapping("/send")
    public void sendMsg() {
        amqpTemplate.convertAndSend("myExchange", "myRoutingKey", "Hello MSG from provider");
    }
}

consumer消費消息

@Component
public class MQReceiver {
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange("myExchange"),
            key = "myRoutingKey",
            value = @Queue("myQueue")
    ))
    public void consume(String msg) {
        System.out.println("rabbit-" + msg);
    }
}

Stream生產和消費消息

provider生產消息

  provider項目增加配置:

spring:
  cloud:
    stream:
      bindings:
        output:
          group: provider
          destination: input
          content-type: application/json

  provider項目生產消息:

@RestController
@RequestMapping("/hello")
@EnableBinding(Source.class)
public class HelloController {
    @Autowired
    private Source source;

    @GetMapping("/stream")
    public void stream() {
        source.output().send(MessageBuilder.withPayload("Stream Hello MSG from provider").build());
    }
}

consumer消費消息

  consumer項目增加配置:

spring:
  cloud:
    stream:
      bindings:
        input:
          group: consumer
          destination: input
          content-type: application/json

  consumer項目消費消息:

@Component
@EnableBinding(Sink.class)
public class MQReceiver {
    @StreamListener(Sink.INPUT)
    public void input(Message<String> message) {
        System.out.println("stream:" + message.getPayload());
    }
}

寫在後面

  不難發現,通過Stream可以極大簡化消息隊列的使用,不管是RabbitMQ還是Kafka,我們只需要關注Stream的使用,如此解耦也可以極大方便我們項目的消息中間件遷移。當然,本系列《Spring Cloud 學習紀要》小博只記錄最簡潔的入門Demo,更高階的使用方法和技巧心得相信聰明的你能夠自己掌握。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章