diff --git a/ruoyi-admin/src/main/java/com/ruoyi/websocket/service/RoomRoomStateService.java b/ruoyi-admin/src/main/java/com/ruoyi/websocket/service/RoomRoomStateService.java new file mode 100644 index 0000000..9498dfe --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/websocket/service/RoomRoomStateService.java @@ -0,0 +1,61 @@ +package com.ruoyi.websocket.service; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +/** + * 房间状态服务:持久化房间内可见航线等状态,供新加入用户同步 + */ +@Service +public class RoomRoomStateService { + + private static final String ROOM_VISIBLE_ROUTES_PREFIX = "room:"; + private static final String ROOM_VISIBLE_ROUTES_SUFFIX = ":visibleRoutes"; + private static final int EXPIRE_HOURS = 24; + + @Autowired + @Qualifier("stringObjectRedisTemplate") + private RedisTemplate redisTemplate; + + private String visibleRoutesKey(Long roomId) { + return ROOM_VISIBLE_ROUTES_PREFIX + roomId + ROOM_VISIBLE_ROUTES_SUFFIX; + } + + /** 更新航线可见状态 */ + public void updateRouteVisibility(Long roomId, Long routeId, boolean visible) { + if (roomId == null || routeId == null) return; + String key = visibleRoutesKey(roomId); + if (visible) { + redisTemplate.opsForSet().add(key, routeId); + } else { + redisTemplate.opsForSet().remove(key, routeId); + } + redisTemplate.expire(key, EXPIRE_HOURS, TimeUnit.HOURS); + } + + /** 获取房间内当前可见的航线 ID 集合 */ + @SuppressWarnings("unchecked") + public Set getVisibleRouteIds(Long roomId) { + if (roomId == null) return new HashSet<>(); + String key = visibleRoutesKey(roomId); + Set raw = redisTemplate.opsForSet().members(key); + Set result = new HashSet<>(); + if (raw != null) { + for (Object o : raw) { + if (o instanceof Number) { + result.add(((Number) o).longValue()); + } else if (o != null) { + try { + result.add(Long.parseLong(o.toString())); + } catch (NumberFormatException ignored) {} + } + } + } + return result; + } +}