Springboot集成阿里消息队列RocketMQ

本文使用Springboot实战一个小demo:

首先得在阿里云创建实例、Topic、Group,然后必看文档:阿里云RocketMQ开发文档

1.依赖:

 // Ali RocketMQ
 compile 'com.aliyun.openservices:ons-client:1.8.0.Final'

2.配置文件:

aliyun:
    rocketmq:
        accessKey: *
        namesrvAddr: *
        secretKey: *
        sendMsgTimeoutMillis: 3000
        tag:
            topicLog: *
        topic:
            gidBoxState: *
        group:
            tagBoxState: *

3.把配置对象化

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Created by xiaoxudong on 2019/3/22
 */
@Component
@ConfigurationProperties(prefix = "aliyun.rocketmq")
public class RocketProperties {

    private String accessKey;
    private String secretKey;
    private String namesrvAddr;
    private String sendMsgTimeoutMillis;
    private Topic topic;
    private Group group;
    private Tag tag;

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getNamesrvAddr() {
        return namesrvAddr;
    }

    public void setNamesrvAddr(String namesrvAddr) {
        this.namesrvAddr = namesrvAddr;
    }

    public String getSendMsgTimeoutMillis() {
        return sendMsgTimeoutMillis;
    }

    public void setSendMsgTimeoutMillis(String sendMsgTimeoutMillis) {
        this.sendMsgTimeoutMillis = sendMsgTimeoutMillis;
    }

    public Topic getTopic() {
        return topic;
    }

    public void setTopic(Topic topic) {
        this.topic = topic;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public Tag getTag() {
        return tag;
    }

    public void setTag(Tag tag) {
        this.tag = tag;
    }

    public static  class Topic{
        private String topicLog;

        public String getTopicLog() {
            return topicLog;
        }

        public void setTopicLog(String topicLog) {
            this.topicLog = topicLog;
        }
    }

    public static  class Group{
        private String gidBoxState;

        public String getGidBoxState() {
            return gidBoxState;
        }

        public void setGidBoxState(String gidBoxState) {
            this.gidBoxState = gidBoxState;
        }
    }
    public static  class Tag{
        private String tagBoxState;

        public String getTagBoxState() {
            return tagBoxState;
        }

        public void setTagBoxState(String tagBoxState) {
            this.tagBoxState = tagBoxState;
        }
    }

}

4.初始化参数及成产者

import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * Created by xiaoxudong on 2019/3/22
 */
@Component
public class RocketMQConfig {
    Logger log = LoggerFactory.getLogger(RocketMQConfig.class);

    @Autowired
    private RocketProperties rp;

    public static Producer producer;
    public static Properties properties;

    /**
     * 初始化参数
     *
     * @return
     */
    public Properties getProperties() {

        if (properties == null) {
            properties = new Properties();
        }
        // AccessKey 阿里云身份验证,在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.AccessKey,rp.getAccessKey() );
        // SecretKey 阿里云身份验证,在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, rp.getSecretKey());
        //设置发送超时时间,单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, rp.getSendMsgTimeoutMillis());
        // 设置 TCP 接入域名,进入控制台的实例管理页面的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                rp.getNamesrvAddr());
        return properties;
    }

    /**
     * 初始化生产者
     *
     * @return
     */
    public Producer getProducer() {
        if (producer == null || producer.isClosed()) {
            producer = ONSFactory.createProducer(properties);
            log.info("===RocketMQ生产者启动===");
            producer.start();
        }
        return producer;
    }

}

5.生产者,这里只写了一种发送,详情见文档

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by xiaoxudong on 2019/3/22
 */
@Component
public class RocketMQProducer {

    @Autowired
    private RocketMQConfig rocketMQConfig;

    /**
     * 普通消息
     * 单向(Oneway)发送
     *
     * @param message
     * @return
     */
    public boolean sendNormalOnewayMessage(Message message) {
        Producer producer = rocketMQConfig.getProducer();
        try {
            // 由于在 oneway 方式发送消息时没有请求应答处理,一旦出现消息发送失败,则会因为没有重试而导致数据丢失。
            producer.sendOneway(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

}

6.消费者,这里可接收多个topic、tag,详情见文档

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.*;
import com.hx.vr.hjhchild.socket.pojo.BoxLog;
import com.hx.vr.hjhchild.socket.service.BoxStateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * Created by xiaoxudong on 2019/3/22
 */
@Component
public class RocketMQConsumer {
    Logger log = LoggerFactory.getLogger(RocketMQConsumer.class);

    @Autowired
    private RocketMQConfig rocketMQConfig;
    @Autowired
    private BoxStateService boxStateService;
    @Autowired
    private RocketProperties rp;

    /**
     * 普通订阅
     * 
     * @param
     */
    public void boxStateConsumer() {

        Properties properties = rocketMQConfig.getProperties();
        properties.put(PropertyKeyConst.GROUP_ID, rp.getGroup().getGidBoxState());
        // 集群订阅方式设置(不设置的情况下,默认为集群订阅方式)
        properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);

        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(rp.getTopic().getTopicLog(), rp.getTag().getTagBoxState(), new MessageListener() {
            @Override
            public Action consume(Message message, ConsumeContext context) {
                log.info(rp.getTag().getTagBoxState() + " Receive: " + new String(message.getBody()));
             
                return Action.CommitMessage;
            }
        });

        consumer.start();
    }

}

7.监听消费者

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * Created by xiaoxudong on 2019/3/22
 */
@Component
public class RocketConsumerListener implements CommandLineRunner {
    Logger log = LoggerFactory.getLogger(RocketConsumerListener.class);

    @Autowired
    private RocketMQConsumer rocketMQConsumer;

    @Override
    public void run(String... args) throws Exception {
        log.info("===RocketMQ消费者启动===");
        rocketMQConsumer.boxStateConsumer();

    }

}

8.写个测试发送

import com.aliyun.openservices.ons.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by xiaoxudong on 2019/3/22
 */
@RestController
public class TestSendMQ {

    @Autowired
    private RocketMQProducer rocketMQProducer;
    @Autowired
    private RocketProperties rp;

    //发送信息
    @RequestMapping("/send")
    public String send(){
        Message message=new Message(
                rp.getTopic().getTopicLog(),
                rp.getTag().getTagBoxState(),
                "Where do you want to go, my lady?".getBytes());
        try {
            rocketMQProducer.sendNormalOnewayMessage(message);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "SUCCESS";
    }

}

注意订阅关系

Springboot集成阿里消息队列RocketMQ_第1张图片

另外,如果两个业务想要消费同一消息,则创建两个group即可,共用相同的topic和tag。

你可能感兴趣的:(Springboot集成阿里消息队列RocketMQ)