java集成rocketmq实现消息发送与消费

引入依赖

<!--    rocketmq    -->
<dependency>
  <groupId>com.aliyun.openservices</groupId>
  <artifactId>ons-client</artifactId>
  <version>1.8.8.5.Final</version>
</dependency>

yml配置

rocketmq:
  accessKey: ${ACCESSKEY}
  secretKey: ${SECRETKEY}
  tcpEndPoint: http://****:8080
  instanceId: ${INSTANCEID}
  tChangeConnection: ${ES_CHANGE_CONNECTION_TOPIC}
  gidChangeConnection: ${ES_CHANGE_CONNECTION_GROUP}

具体代码

加载配置

@Data
@Component
@ConfigurationProperties(prefix = "rocketmq")
public class RocketMQProperties {
    private String accessKey;
    private String secretKey;
    private String tcpEndPoint;
    private String httpEndPoint;
    private String instanceId;
    private String tChangeConnection;
    private String gidChangeConnection;
}

注入生产者

import cn.hutool.core.date.DateUtil;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;
@Slf4j
@Configuration
public class ProducerClient {

    @Autowired
    private RocketMQProperties rocketMQProperties;

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ProducerBean buildProducer() {
        Properties properties = new Properties();
        // AccessKey ID阿里云身份验证,在阿里云RAM控制台创建。
        properties.put(PropertyKeyConst.AccessKey, rocketMQProperties.getAccessKey());
        // Accesskey Secret阿里云身份验证,在阿里云服RAM控制台创建。
        properties.put(PropertyKeyConst.SecretKey, rocketMQProperties.getSecretKey());
        // 设置TCP接入域名,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
        properties.put(PropertyKeyConst.NAMESRV_ADDR, rocketMQProperties.getTcpEndPoint());
        ProducerBean producer = new ProducerBean();
        producer.setProperties(properties);
        log.info("init producer success,init time:{}", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        return producer;
    }

}

启动消费者

方式一

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class ConsumerClient {

    @Autowired
    private RocketMQProperties rocketMQProperties;

    @Autowired
    private DemoMessageListener messageListener;

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ConsumerBean buildConsumer() {
        ConsumerBean consumerBean = new ConsumerBean();
        //配置文件
        Properties properties = new Properties();
        // 您在控制台创建的Group ID。
        properties.put(PropertyKeyConst.GROUP_ID, rocketMQProperties.getGidChangeConnection());
        // AccessKey ID阿里云身份验证,在阿里云RAM控制台创建。
        properties.put(PropertyKeyConst.AccessKey, rocketMQProperties.getAccessKey());
        // Accesskey Secret阿里云身份验证,在阿里云服RAM控制台创建。
        properties.put(PropertyKeyConst.SecretKey, rocketMQProperties.getSecretKey());
        // 设置TCP接入域名,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
        properties.put(PropertyKeyConst.NAMESRV_ADDR, rocketMQProperties.getTcpEndPoint());
        // 集群订阅方式(默认)。
        properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
        properties.put(PropertyKeyConst.INSTANCE_ID, rocketMQProperties.getInstanceId());
        //将消费者线程数固定为20个 20为默认值
        properties.setProperty(PropertyKeyConst.ConsumeThreadNums, "20");
        consumerBean.setProperties(properties);
        //订阅关系
        Map<Subscription, MessageListener> subscriptionTable = new HashMap<Subscription, MessageListener>();
        Subscription subscription = new Subscription();
        subscription.setTopic(rocketMQProperties.getTChangeConnection());
        subscriptionTable.put(subscription, messageListener);
        //订阅多个topic如上面设置

        consumerBean.setSubscriptionTable(subscriptionTable);
        return consumerBean;
    }

}
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import org.springframework.stereotype.Component;

@Component
public class DemoMessageListener implements MessageListener {

    @Override
    public Action consume(Message message, ConsumeContext context) {

        System.out.println("Receive: " + message);
        try {
            //do something..
            return Action.CommitMessage;
        } catch (Exception e) {
            //消费失败
            return Action.ReconsumeLater;
        }
    }
}

方式二

Properties properties = new Properties();
// 您在控制台创建的Group ID。
properties.put(PropertyKeyConst.GROUP_ID, rocketMQProperties.getGidChangeConnection());
// AccessKey ID阿里云身份验证,在阿里云RAM控制台创建。
properties.put(PropertyKeyConst.AccessKey, rocketMQProperties.getAccessKey());
// Accesskey Secret阿里云身份验证,在阿里云服RAM控制台创建。
properties.put(PropertyKeyConst.SecretKey, rocketMQProperties.getSecretKey());
// 设置TCP接入域名,进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
properties.put(PropertyKeyConst.NAMESRV_ADDR, rocketMQProperties.getTcpEndPoint());
// 集群订阅方式(默认)。
properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
properties.put(PropertyKeyConst.INSTANCE_ID, rocketMQProperties.getInstanceId());
//创建Consumer
Consumer consumer = ONSFactory.createConsumer(properties);
consumer.subscribe(rocketMQProperties.getTChangeConnection(), "*", (message, consumeContext) -> {
    Date date = DateUtil.date();
    String content = new String(message.getBody());
    log.info("consumer received message:{},receive time:{}", content, DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS"));
    return Action.CommitMessage;
});
consumer.start();
log.info("rocketmq consumer start success,start time {}", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss.SSS"));

posted @ 2023-01-11 11:25  未月廿三  阅读(939)  评论(0编辑  收藏  举报