RabbitMQ--05--Spring Cloud Stream(消息驱动)
在Spring Cloud Stream中,我们可以通过定义接收器(Sink)和发送器(Source)来实现消息驱动的微服务。以下是一个简单的例子,展示如何使用Spring Cloud Stream发送和接收消息。
首先,在pom.xml
中添加Spring Cloud Stream和RabbitMQ依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
</dependencies>
然后,在application.yml
中配置Spring Cloud Stream和RabbitMQ:
spring:
cloud:
stream:
binders:
defaultRabbit:
type: rabbit
environment:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
bindings:
input:
destination: my-input-topic
content-type: application/json
group: my-consumer-group
output:
destination: my-output-topic
content-type: application/json
发送消息的代码示例:
@EnableBinding(Source.class)
public class MessageSender {
@Autowired
private MessageChannel output;
public void sendMessage(String message) {
this.output.send(MessageBuilder.withPayload(message).build());
}
}
接收消息的代码示例:
@EnableBinding(Sink.class)
public class MessageReceiver {
@StreamListener(Sink.INPUT)
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
在这个例子中,我们定义了一个名为input
的输入通道和一个名为output
的输出通道,并且通过@EnableBinding
注解指定了使用Sink和Source。通过MessageSender
的sendMessage
方法,我们可以向my-output-topic
发送消息,而MessageReceiver
的receiveMessage
方法则会监听my-input-topic
的消息,并在接收到消息时打印出来。
评论已关闭