package com.iot.modbus_rtcp.config; import cn.hutool.core.map.MapUtil; import com.iot.modbus_rtcp.utils.HexUtil; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; @Service @RequiredArgsConstructor public class EquipmentIPProperties { private final JdbcTemplate jdbcTemplate; private final AtomicLong lastSyncEquipment = new AtomicLong(System.currentTimeMillis()); private final Map identifiers = new ConcurrentHashMap<>(); public String get(String key) { return this.identifiers.get(key); } public String put(String gatewaySn) { String gatewayHeartbeat = HexUtil.bytesToHexString(gatewaySn.getBytes()).toUpperCase(); this.identifiers.put(gatewayHeartbeat, gatewaySn); return gatewayHeartbeat; } public boolean contains(String gatewayHeartbeat) { if (this.identifiers.containsKey(gatewayHeartbeat)) { return true; } if (gatewayHeartbeat.length() > 80) { return false; } // 每分钟从数据库入库一次 if (this.lastSyncEquipment.getAcquire() > System.currentTimeMillis() - 60_000) { this.jdbcTemplate.queryForList("select gateway_sn from device").forEach(map -> { String gatewaySn = StringUtils.trim(MapUtil.getStr(map, "gateway_sn", "")); if (StringUtils.isNotBlank(gatewaySn)) { this.identifiers.put(HexUtil.bytesToHexString(gatewaySn.getBytes()).toUpperCase(), gatewaySn); } }); this.lastSyncEquipment.setRelease(System.currentTimeMillis()); } return this.identifiers.containsKey(gatewayHeartbeat); } }