1 changed files with 61 additions and 0 deletions
@ -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<String, Object> 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<Long> getVisibleRouteIds(Long roomId) { |
|||
if (roomId == null) return new HashSet<>(); |
|||
String key = visibleRoutesKey(roomId); |
|||
Set<Object> raw = redisTemplate.opsForSet().members(key); |
|||
Set<Long> 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; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue