欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot集成RocketMQ

程序员文章站 2022-06-28 17:42:46
引入RocketMQ org.apache.rocketmq rocketmq-spring-boot-starter 2.0.3

引入 RocketMQ

        <dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>

Producer实现

配置文件

rocketmq:
  name-server: xxx
  producer:
    access-key: xxx
    secret-key: xxx
    group: xxx
    topic:
      xzh: xxx
    tag:
      xzh: xxx

发送实现

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 消息发送
 *
 * @author: 向振华
 * @date: 2020/11/30 10:28
 */
@Component
public class RocketMQProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.producer.topic.xzh}")
    private String topic;

    @Value("${rocketmq.producer.tag.xzh}")
    private String tag;

    public void send(String msg) {
        if (StringUtils.isBlank(msg)) {
            return;
        }
        rocketMQTemplate.syncSend(topic + ":" + tag, msg);
    }
}

Consumer实现

配置文件

rocketmq:
  name-server: xxx
  consumer:
    access-key: xxx
    secret-key: xxx
    group: xxx
    topic:
      xzh: xxx
    tag:
      xzh: xxx

接受实现

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * 消息接收
 *
 * @author: 向振华
 * @date: 2020/11/30 10:28
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumer.group}", topic = "${rocketmq.consumer.topic.xzh}", selectorExpression = "${rocketmq.consumer.tag.xzh}")
public class RocketMQConsumerListener implements RocketMQListener<String> {

    @Override
    public void onMessage(String msg) {
        log.info("接收到消息 -> " + msg);
    }
}

 

本文地址:https://blog.csdn.net/Anenan/article/details/110379786

相关标签: Spring系列