一、说明
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: +使用通配符
~~