本節介紹Spring Cloud Stream的編程模型。Spring Cloud Stream提供了許多預定義的注釋,用於聲明綁定的輸入和輸出通道,以及如何收聽頻道。
聲明和綁定頻道
觸發綁定@EnableBinding
您可以將Spring應用程序轉換為Spring Cloud Stream應用程序,將@EnableBinding
注釋應用於應用程序的配置類之一。@EnableBinding
注釋本身使用@Configuration
進行元注釋,並觸發Spring Cloud Stream基礎架構的配置:
... @Import(...) @Configuration @EnableIntegration public @interface EnableBinding { ... Class<?>[] value() default {}; }
@EnableBinding
注釋可以將一個或多個接口類作為參數,這些接口類包含表示可綁定組件(通常是消息通道)的方法。
注意
|
在Spring Cloud Stream 1.0中,唯一支持的可綁定組件是Spring消息傳遞 |
@Input
和@Output
Spring Cloud Stream應用程序可以在接口中定義任意數量的輸入和輸出通道為@Input
和@Output
方法:
public interface Barista { @Input SubscribableChannel orders(); @Output MessageChannel hotDrinks(); @Output MessageChannel coldDrinks(); }
使用此接口作為參數@EnableBinding
將分別觸發三個綁定的通道名稱為orders
,hotDrinks
和coldDrinks
。
@EnableBinding(Barista.class) public class CafeConfiguration { ... }
自定義頻道名稱
使用@Input
和@Output
注釋,您可以指定頻道的自定義頻道名稱,如以下示例所示:
public interface Barista { ... @Input("inboundOrders") SubscribableChannel orders(); }
在這個例子中,創建的綁定通道將被命名為inboundOrders
。
Source
,Sink
和Processor
為了方便尋址最常見的用例,涉及輸入通道,輸出通道或兩者,Spring Cloud Stream提供了開箱即用的三個預定義接口。
Source
可用於具有單個出站通道的應用程序。
public interface Source { String OUTPUT = "output"; @Output(Source.OUTPUT) MessageChannel output(); }
Sink
可用於具有單個入站通道的應用程序。
public interface Sink { String INPUT = "input"; @Input(Sink.INPUT) SubscribableChannel input(); }
Processor
可用於具有入站通道和出站通道的應用程序。
public interface Processor extends Source, Sink { }
Spring Cloud Stream不為任何這些接口提供特殊處理; 它們只是開箱即用。源碼來源