package com.vincent.rsf.server.ai.store.support;
|
|
import com.fasterxml.jackson.core.type.TypeReference;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.vincent.rsf.server.common.service.RedisService;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Component;
|
import org.springframework.util.StringUtils;
|
import redis.clients.jedis.Jedis;
|
|
import java.util.function.Consumer;
|
import java.util.function.Function;
|
|
@Slf4j
|
@Component
|
@RequiredArgsConstructor
|
public class AiRedisExecutor {
|
|
private final RedisService redisService;
|
private final ObjectMapper objectMapper;
|
|
public <T> T readJson(String key, Class<T> type) {
|
return readJson(key, value -> objectMapper.readValue(value, type));
|
}
|
|
public <T> T readJson(String key, TypeReference<T> typeReference) {
|
return readJson(key, value -> objectMapper.readValue(value, typeReference));
|
}
|
|
public <T> T readJson(String key, JsonReader<T> reader) {
|
return execute(jedis -> {
|
String value = jedis.get(key);
|
if (!StringUtils.hasText(value)) {
|
return null;
|
}
|
try {
|
return reader.read(value);
|
} catch (Exception e) {
|
log.warn("AI redis cache deserialize failed, key={}, message={}", key, e.getMessage());
|
jedis.del(key);
|
return null;
|
}
|
});
|
}
|
|
public void writeJson(String key, Object value, int ttlSeconds) {
|
if (value == null) {
|
delete(key);
|
return;
|
}
|
executeVoid(jedis -> {
|
try {
|
jedis.setex(key, ttlSeconds, objectMapper.writeValueAsString(value));
|
} catch (Exception e) {
|
log.warn("AI redis cache serialize failed, key={}, message={}", key, e.getMessage());
|
}
|
});
|
}
|
|
public void delete(String key) {
|
executeVoid(jedis -> jedis.del(key));
|
}
|
|
public <T> T execute(Function<Jedis, T> action) {
|
Jedis jedis = redisService.getJedis();
|
if (jedis == null) {
|
return null;
|
}
|
try (jedis) {
|
return action.apply(jedis);
|
} catch (Exception e) {
|
log.warn("AI redis operation skipped, message={}", e.getMessage());
|
return null;
|
}
|
}
|
|
public void executeVoid(Consumer<Jedis> action) {
|
Jedis jedis = redisService.getJedis();
|
if (jedis == null) {
|
return;
|
}
|
try (jedis) {
|
action.accept(jedis);
|
} catch (Exception e) {
|
log.warn("AI redis operation skipped, message={}", e.getMessage());
|
}
|
}
|
|
@FunctionalInterface
|
public interface JsonReader<T> {
|
T read(String value) throws Exception;
|
}
|
}
|