RocketMQ内容分享:消费者和生产者、SpringBoot集成、Spring Cloud Stream集成
以下是RocketMQ与Spring Boot和Spring Cloud Stream集成的示例代码:
Spring Boot 集成 RocketMQ
- 添加依赖到
pom.xml
:
<dependencies>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
- 配置application.properties:
rocketmq.name-server=127.0.0.1:9876
rocketmq.producer.group=my-group
- 发送消息的生产者:
@Component
public class Producer {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public void sendMessage(String topic, String message) {
rocketMQTemplate.convertAndSend(topic, message);
}
}
- 接收消息的消费者:
@Component
@RocketMQMessageListener(topic = "my-topic", consumerGroup = "my-consumer_group")
public class Consumer implements RocketMQListener<String> {
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
}
Spring Cloud Stream 集成 RocketMQ
- 添加依赖到
pom.xml
:
<dependencies>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>
</dependencies>
- 配置application.properties:
spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876
spring.cloud.stream.bindings.input.destination=my-topic
spring.cloud.stream.bindings.input.group=my-consumer_group
spring.cloud.stream.bindings.output.destination=my-topic
spring.cloud.stream.bindings.output.group=my-producer_group
- 发送消息:
@EnableBinding(Source.class)
public class Producer {
@Autowired
private MessageChannel output;
public void sendMessage(String message) {
output.send(MessageBuilder.withPayload(message).build());
}
}
- 接收消息:
@EnableBinding(Sink.class)
public class Consumer {
@StreamListener(Sink.INPUT)
public void receive(String message) {
System.out.println("Received message: " + message);
}
}
以上代码展示了如何在Spring Boot和Spring Cloud Stream中集成RocketMQ作为消息队列。在Spring Boot中,使用\`rocketmq-spring-boot-start
评论已关闭