【Java】 java | mqtt | 消息订阅 | 分组订阅 | 业务处理 | 正则表达式 | 通配符

一、说明

        1、springboot项目

        2、集成mqtt

        3、mqtt分组订阅topic

        4、策略模式按业务区分处理

        5、topic含有业务标识

二、解决

1、看枚举类


/**
 * 订阅者topic
 * @author https://i.hgsuper.cn
 * @date 2022-11-08
 */
@Getter
@AllArgsConstructor
public enum SubTopicEnum {
    /**
     * 塔石读阳光电源逆变器
     * +, 即SN号
     */
    YANG_GUANG_DIAN_YUAN("$share/yangguang/v1/client/server/+", v1/client/server/+", "阳光电源逆变器",null),
    ;
    /**
     * 分组订阅
     */
    private String shareTopic;
    /**
     * 实际topic
     */
    private String realTopic;
    /**
     * 描述
     */
    private String text;
    /**
     * 消息处理
     */
    private Class<? extends MqttBizHandler> bizHandler;

    /**
     * 通过topic获取处理器
     * @param topic
     * @return 可能为null
     */
    public static MqttBizHandler byTopic(String topic) {
        // 正则表达topic
        String regularTopic = null;
        for (SubTopicEnum i : SubTopicEnum.values()) {
            regularTopic = transferTopic(i.realTopic);
            if (StringUtils.isMatch(regularTopic, topic)) {
                // 正则匹配
                // eg: citcc4-gcy/tashi/server/v2/+
                return SpringUtil.getBean(i.getBizHandler());
            }
        }
        // 未定义
        return null;
    }

    /**
     * mqtt.topic转换为java.正则表达式
     * 正则匹配topic
     * @param topic
     * @return
     */
    static String transferTopic(String topic) {
        return topic
                .replaceAll("\\+", "*")
                .replaceAll("#", "*")
                ;
    }
}

说明1: +使用通配符

~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值