消息中间件——RabbitMQRabbitMQ整合Spring Cloud Stream实战!
@EnableBinding(Sink.class)
public class LoggingConsumer {
private static Logger logger = LoggerFactory.getLogger(LoggingConsumer.class);
@StreamListener(Sink.INPUT)
public void handle(Person person) {
logger.info("Received: " + person);
}
}
@EnableBinding(Source.class)
public class MainApplication {
private static Logger logger = LoggerFactory.getLogger(MainApplication.class);
@Autowired
private MessageChannel output;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Scheduled(fixedDelay = 1000)
public void sendMessage() {
if(output != null) {
Person person = new Person("John Doo", 34);
logger.info("Sending: " + person);
output.send(MessageBuilder.withPayload(person).build());
}
}
}
在这个例子中,我们定义了一个消息接收者LoggingConsumer
,它使用@StreamListener
注解来监听输入消息,并将接收到的Person
对象的信息记录到日志中。MainApplication
类则定义了一个计划任务,每隔一秒钟向RabbitMQ发送一条消息。这个例子展示了如何使用Spring Cloud Stream与RabbitMQ进行消息的发送和接收。
评论已关闭