package cn.netkiller.service;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.function.Supplier;
@Service
@Slf4j
public class CacheService {
@Autowired
private RedisTemplate redisTemplate;
private final String prefix = "service";
@SneakyThrows
public static String md5Key(String key) {
String digest = DatatypeConverter
.printHexBinary(MessageDigest.getInstance("MD5").digest(key.getBytes(StandardCharsets.UTF_8)));
return digest;
}
public <T> T cache(String cacheKey, Duration duration, Supplier<T> supplier) {
// RedisTemplate redisTemplate = new RedisTemplate();
String key = String.format("%s:%s", prefix, cacheKey);
T value;
if (redisTemplate == null) {
value = supplier.get();
log.info("Cache Skip Key: " + key + " Value: " + value);
} else {
if (redisTemplate.hasKey(key)) {
value = (T) redisTemplate.opsForValue().get(key);
log.info("Cache Hit Key: " + key + " Value: " + value);
} else {
value = supplier.get();
if (value != null) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.opsForValue().set(key, value);
redisTemplate.expire(key, duration);
log.info("Cache Set Key: " + key + " Value: " + value);
} else {
log.info("Cache Set Key: " + key + " Error: " + value);
}
}
}
return value;
}
}