TopicUtil.java 2.3 KB
package vion.utils;

import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.extra.spring.SpringUtil;
import org.redisson.api.RedissonClient;
import vion.constant.AgentTypeEnum;
import vion.constant.MqttTopic;
import vion.constant.RedisKeyEnum;
import vion.model.monitor.Agent;
import vion.service.monitor.IAgentService;

/**
 * @author vion
 * @date 2024/11/4
 */
@Slf4j
public class TopicUtil {

    public static String getEventTopic(String agentUid) {
        return getTopic(agentUid, MqttTopic.STORE_EVENT_TOPIC, MqttTopic.MALL_EVENT_TOPIC);
    }

    public static String getServiceTopic(String agentUid) {
        return getTopic(agentUid, MqttTopic.STORE_SERVICE_TOPIC, MqttTopic.MALL_SERVICE_TOPIC);
    }

    public static String getOTATopic(String agentUid) {
        return getTopic(agentUid, MqttTopic.STORE_OTA_TOPIC, MqttTopic.MALL_OTA_TOPIC);
    }

    private static String getTopic(String agentUid, String storeTopic, String mallTopic) {
        var agent = getAgent(agentUid);
        if (agent == null) {
            return null;
        }
        if (NumberUtil.equals(agent.getType(), AgentTypeEnum.STORE.getCode())) {
            return StrUtil.format(storeTopic, agentUid);
        } else if (ObjUtil.equals(agent.getType(), AgentTypeEnum.MALL.getCode())) {
            return StrUtil.format(mallTopic, agentUid);
        } else {
            log.info("未知的agent类型");
            return null;
        }
    }

    private static Agent getAgent(String agentUid) {
        var redissonClient = SpringUtil.getBean(RedissonClient.class);
        var agent = (Agent) redissonClient.getBucket(RedisKeyEnum.AGENT.getVal() + agentUid).get();
        if (ObjUtil.isNull(agent)) {
            var agentService = SpringUtil.getBean(IAgentService.class);
            var agentList = agentService.list();
            agentList.forEach(a -> redissonClient.getBucket(RedisKeyEnum.AGENT.getVal() + a.getUid()).set(a));
            agent = agentList.stream().filter(a -> StrUtil.equals(a.getUid(), agentUid)).findFirst().orElse(null);
        }
        if (ObjUtil.isNull(agent)) {
            log.info("未找到agent信息");
            return null;
        }
        return agent;
    }
}