package com.ruoyi.config;
|
|
import java.util.List;
|
import java.util.concurrent.TimeUnit;
|
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.stereotype.Component;
|
import com.alibaba.fastjson2.JSON;
|
import com.alibaba.fastjson2.JSONObject;
|
import com.ruoyi.device.simulator.BtsSimulatorStateStore;
|
|
/** 将开发模拟器完整状态写入 Redis,主状态不设置普通 TTL。 */
|
@Component
|
public class RedisBtsSimulatorStateStore implements BtsSimulatorStateStore
|
{
|
static final String STATE_KEY = "dev:bts-simulator:state:v1";
|
static final String RECENT_REQUESTS_KEY = "dev:bts-simulator:recent-requests:v1";
|
private static final long RECENT_REQUESTS_TTL_HOURS = 1;
|
|
private final RedisTemplate<Object, Object> redisTemplate;
|
|
public RedisBtsSimulatorStateStore(RedisTemplate<Object, Object> redisTemplate)
|
{
|
this.redisTemplate = redisTemplate;
|
}
|
|
@Override
|
public SimulatorState loadOrInitialize(SimulatorState defaultState)
|
{
|
Object stored = redisTemplate.opsForValue().get(STATE_KEY);
|
if (stored != null) return parseState(stored);
|
String initial = JSON.toJSONString(defaultState);
|
if (Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(STATE_KEY, initial))) return defaultState;
|
stored = redisTemplate.opsForValue().get(STATE_KEY);
|
if (stored == null) throw new IllegalStateException("BTS simulator state initialization lost in Redis");
|
return parseState(stored);
|
}
|
|
@Override
|
public void save(SimulatorState state)
|
{
|
redisTemplate.opsForValue().set(STATE_KEY, JSON.toJSONString(state));
|
}
|
|
@Override
|
public List<RecentRequest> loadRecentRequests()
|
{
|
Object stored = redisTemplate.opsForValue().get(RECENT_REQUESTS_KEY);
|
if (stored == null) return List.of();
|
return List.copyOf(JSON.parseArray(stored.toString(), RecentRequest.class));
|
}
|
|
@Override
|
public void saveRecentRequests(List<RecentRequest> requests)
|
{
|
redisTemplate.opsForValue().set(RECENT_REQUESTS_KEY, JSON.toJSONString(requests),
|
RECENT_REQUESTS_TTL_HOURS, TimeUnit.HOURS);
|
}
|
|
@Override
|
public void reset(SimulatorState defaultState)
|
{
|
redisTemplate.delete(RECENT_REQUESTS_KEY);
|
save(defaultState);
|
}
|
|
private SimulatorState parseState(Object stored)
|
{
|
try
|
{
|
String json = stored.toString();
|
JSONObject root = JSON.parseObject(json);
|
Integer version = root.getInteger("version");
|
if (version == null || version != CURRENT_VERSION)
|
throw new IllegalStateException("Unsupported BTS simulator state version: " + version);
|
return JSON.parseObject(json, SimulatorState.class);
|
}
|
catch (IllegalStateException exception)
|
{
|
throw exception;
|
}
|
catch (Exception exception)
|
{
|
throw new IllegalStateException("Invalid BTS simulator state in Redis", exception);
|
}
|
}
|
}
|