在Spring Cloud 分布式消息—Spring Cloud Stream 简介与入门一篇我们简单了介绍了Spring Cloud Stream,并且使用Spring Cloud Stream提供的默认通道input,output简单的做了一个示例,本篇我们将会使用自定义通道做一个示例,并且介绍Spring Cloud Stream的高级应用,如果对Spring Cloud Stream 不了解可以先去阅读Spring Cloud 分布式消息—Spring Cloud Stream 简介与入门一篇文章。
在上一篇我们介绍了两个注解@Input和@Output分别用于定义输入和输出通道,Spring Cloud Stream定义的SInk和Source就是使用了这两个注解。我们自定义通道也需要使用这两个注解,使用这两个注解,我们很容易定义输入和输出通道,比如我们定义一个日志的输入输出通道,代码如下:
//定义日志输入通道
public interface LogSink {
String INPUT = "logInput";
@Input("logInput")
SubscribableChannel input();
}
//定义日志输出通道
public interface LogSource {
String OUTPUT = "logOutput";
@Output("logOutput")
MessageChannel output();
}
在编写在通道之后,我们需要在配置文件中定义通道,将通道绑定到binder,并且为binder绑定到消息中间件,上面的通道配置如下:
spring:
cloud:
stream:
bindings: #用于绑定通道到binder
logInput: #ChannelName 这里是输入通道的名称,如果@Input不指定默认为方法名
destination: log #从哪里接收消息,这里指topic或者队列名称,在rabbit中为exchange
binder: logBinder #绑定到名为logBinder的binder
logOutput: #ChannelName 这里是输出通道的名称,如果@Output不指定默认为方法名
destination: log #将消息发送到哪里,这里指topic或者队列名称,在rabbit中为e