spring cloud sream 统一集成mq中间件
Spring Cloud Stream 是一个构建消息驱动微服务的框架,可以统一整合不同的消息中间件,如RabbitMQ和Kafka。
以下是一个使用Spring Cloud Stream整合RabbitMQ的简单示例:
- 在
pom.xml
中添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置application.yml:
spring:
cloud:
stream:
binders:
defaultRabbit:
type: rabbit
environment:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
bindings:
input:
destination: my-input-topic
binder: defaultRabbit
group: my-consumer-group
output:
destination: my-output-topic
binder: defaultRabbit
- 创建接收消息的服务类:
@EnableBinding(Sink.class)
public class Receiver {
@StreamListener(Sink.INPUT)
public void receive(String payload) {
System.out.println("Received: " + payload);
}
}
- 创建发送消息的服务类:
@EnableBinding(Source.class)
public class Sender {
@Autowired
private MessageChannel output;
public void send(String message) {
this.output.send(MessageBuilder.withPayload(message).build());
}
}
以上代码展示了如何使用Spring Cloud Stream来接收和发送消息。在这个例子中,我们使用RabbitMQ作为消息中间件,并定义了输入和输出通道。通过@EnableBinding
注解绑定通道,并通过@StreamListener
注解监听输入通道上的消息。发送者通过注入MessageChannel
来发送消息。
评论已关闭