Spring Cloud Stream教程(一)介绍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);
  }
}

  

@EnableBinding注释需要一个或多个接口作为参数(在这种情况下,该参数是单个Sink接口)。接口声明输入和/或输出通道。Spring Cloud Stream提供了接口SourceSinkProcessor; 您还可以定义自己的界面。

以下是Sink接口的定义:

public interface Sink {
  String INPUT = "input";

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

  

@Input注释标识输入通道,通过该输入通道接收到的消息进入应用程序; @Output注释标识输出通道,发布的消息将通过该通道离开应用程序。@Input@Output注释可以使用频道名称作为参数; 如果未提供名称,将使用注释方法的名称。

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());
  }
}

  源码来源

posted @ 2018-02-02 10:50  allalongx  阅读(1301)  评论(1编辑  收藏  举报