| | |
| | | * 订阅指定设备的数据 |
| | | */ |
| | | public void subscribe(String boxSn, Long userId, Integer period) { |
| | | subscriptions.computeIfAbsent(boxSn, k -> new HashSet<>()).add(userId); |
| | | subscriptions.computeIfAbsent(boxSn, k -> ConcurrentHashMap.newKeySet()).add(userId); |
| | | if (subscriptions.get(boxSn).size() == 1) { |
| | | log.debug("首次订阅,启动推送任务"); |
| | | startPushTask(boxSn, period); |
| | | } |
| | | } |
| | |
| | | * 取消订阅 |
| | | */ |
| | | public void unsubscribe(String boxSn, Long userId) { |
| | | Set<Long> userIds = subscriptions.get(boxSn); |
| | | if (userIds != null) { |
| | | subscriptions.compute(boxSn, (key, userIds) -> { |
| | | if (userIds == null) { |
| | | return null; |
| | | } |
| | | userIds.remove(userId); |
| | | if (userIds.isEmpty()) { |
| | | stopPushTask(boxSn); |
| | | log.debug("无人订阅设备 {},移除订阅记录", boxSn); |
| | | return null; // 直接返回 null 等价于 remove(key) |
| | | } |
| | | return userIds; |
| | | }); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 启动推送任务 |
| | | */ |
| | |
| | | return; |
| | | } |
| | | ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> { |
| | | try { |
| | | sendDataToSubscribers(boxSn); |
| | | } catch (Exception e) { |
| | | log.error("Error in push task for boxSn={}", boxSn, e); |
| | | } |
| | | }, 0, period, TimeUnit.SECONDS); |
| | | |
| | | pushTasks.put(boxSn, future); |