spring cloud stream可以用来简化消息中间件的使用
1,加上依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
2,应用
public interface StreamClient {
@Input("myMessage1")
SubscribableChannel input();
@Output("myMessage")
MessageChannel output();
}
@Component
@EnableBinding(StreamClient.class)
@Slf4j
public class StreamReceiver {
@StreamListener("myMessage")
public void process(Object message) {
log.info("myMessage : {}", message );
}
}
@RestController
public class SendMessageController {
@Autowired
private StreamClient streamClient;
@GetMapping("/sendMessage")
public void process() {
String message ="now " + new Date();
streamClient.output().send(MessageBuilder.withPayload(message).build());
}
}
这样一访问 http://localhost:8090/sendMessage 就会在控制台打印:
myMessage1 : [110, 111, 119, 32, 84, 117, 101, 32, 77, 97, 114, 32, 49, 50, 32, 49, 53, 58, 48, 48, 58, 53, 57, 32, 67, 83, 84, 32, 50, 48, 49, 57]
3.消息的分组
如果启动了两个实例,这时候对第一个实例访问/sendMessage,两个实例都会收到消息,这是我们不想看到的,这时候在bootstrap.yml加入如下设置:
stream:
bindings:
myMessage:
group: order
这时候只有一个实例会收到消息,这就是所谓的消息的分组。如果加上content-type:
stream:
bindings:
myMessage:
group: order
content-type: application/json
那么就可以在消息队列中显示出具体内容。