| | |
| | | import java.sql.ResultSet; |
| | | import java.sql.SQLException; |
| | | import java.util.ArrayList; |
| | | import java.util.Collections; |
| | | import java.util.List; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | |
| | | public class Dell_BaseStation { |
| | | static List<LocationBaseStation> baseStations; |
| | | public static List<LocationBaseStation> baseStations; |
| | | private static ConcurrentHashMap<String, LocationBaseStation> baseStationMap; // 以基站ID为键的映射 |
| | | |
| | | public static List<LocationBaseStation> getBaseStations() throws SQLException { |
| | | baseStations = new ArrayList<>(); |
| | | baseStationMap = new ConcurrentHashMap<>(); // 修复:初始化映射 |
| | | ResultSet rs = DBConnector.queryTableData("location_base_station"); |
| | | |
| | | if (rs == null) { |
| | | // 说明底层拿不到数据,直接抛异常或打印日志 |
| | | throw new SQLException("DBConnector.queryTableData returned null, " |
| | | + "please check database connection & SQL."); |
| | | } |
| | | while (rs.next()) { |
| | | LocationBaseStation baseStation = new LocationBaseStation(); |
| | | baseStation.setId((int) rs.getLong("id")); |
| | |
| | | return baseStationMap.get(baseStationId); // O(1)复杂度直接获取 |
| | | } |
| | | |
| | | /** |
| | | * 获取所有在线状态(onlineStatus=1)的设备(高效内存操作) |
| | | * @return 不可修改的baseStationMap集合(避免外部修改缓存) |
| | | */ |
| | | public static List<LocationBaseStation> getOnlineBaseStations() { |
| | | if (baseStationMap == null || baseStationMap.isEmpty()) { |
| | | return Collections.emptyList(); // 缓存为空时返回空集合 |
| | | } |
| | | |
| | | List<LocationBaseStation> BaseStation = new ArrayList<>(); |
| | | for (LocationBaseStation base : baseStationMap.values()) { |
| | | if ("1".equals(base.getStatus())) { // 字符串比较避免NPE |
| | | BaseStation.add(base); |
| | | } |
| | | } |
| | | return Collections.unmodifiableList(BaseStation); // 返回不可变集合 |
| | | } |
| | | |
| | | /** |
| | | * 快速获取LocationTag对象的总数(使用内存缓存提高性能) |
| | | * @return LocationTag对象的总数 |
| | | */ |
| | | public static int getLocationBaseCount() { |
| | | if (baseStationMap == null) { |
| | | synchronized (LocationBaseStation.class) { |
| | | if (baseStationMap == null) { |
| | | try { |
| | | getBaseStations(); // 初始化缓存 |
| | | } catch (SQLException e) { |
| | | e.printStackTrace(); |
| | | return 0; // 初始化失败返回0 |
| | | } |
| | | } |
| | | } |
| | | } |
| | | return baseStationMap.size(); |
| | | } |
| | | |
| | | } |