27. 介绍 Spring Cloud Stream

Spring Cloud Stream 是用于构建消息驱动的微服务应用程序的框架。 Spring Cloud Stream 基于 Spring Boot 来创建独立的生产级 Spring 应用程序,并使用 Spring Integration 提供与消息代理的连接。它提供了来自多家供应商的中间件的合理配置,并介绍了持久性发布-订阅语义,使用者组和分区的概念。

您可以在应用程序中添加@EnableBinding注解,以立即连接到消息代理,还可以在方法中添加@StreamListener,以使其接收流处理的事件。以下示例显示了接收外部消息的接收器应用程序:

@SpringBootApplication
@EnableBinding(Sink.class)
public class VoteRecordingSinkApplication {

  public static void main(String[] args) {
    SpringApplication.run(VoteRecordingSinkApplication.class, args);
  }

  @StreamListener(Sink.INPUT)
  public void processVote(Vote vote) {
      votingService.recordVote(vote);
  }
}

@EnableBindingComments 将一个或多个接口作为参数(在这种情况下,该参数是单个Sink接口)。接口声明 Importing 和输出通道。 Spring Cloud Stream 提供了SourceSinkProcessor接口。您也可以定义自己的接口。

以下清单显示了Sink接口的定义:

public interface Sink {
  String INPUT = "input";

  @Input(Sink.INPUT)
  SubscribableChannel input();
}

@InputComments 标识 Importing 通道,接收的消息通过该 Importing 通道进入应用程序。 @OutputComments 标识一个输出通道,已发布的消息通过该输出通道离开应用程序。 @Input@Output注解可以使用通道名称作为参数。如果未提供名称,则使用带 Comments 的方法的名称。

Spring Cloud Stream 为您创建接口的实现。您可以通过自动装配在应用程序中使用它,如以下示例所示(来自测试用例):

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = VoteRecordingSinkApplication.class)
@WebAppConfiguration
@DirtiesContext
public class StreamApplicationTests {

  @Autowired
  private Sink sink;

  @Test
  public void contextLoads() {
    assertNotNull(this.sink.input());
  }
}