68 lines
1.8 KiB
Java
68 lines
1.8 KiB
Java
package com.dlp.admin.util;
|
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import lombok.AllArgsConstructor;
|
|
import org.springframework.data.redis.core.RedisTemplate;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import java.time.Duration;
|
|
import java.util.Optional;
|
|
|
|
@Component
|
|
@AllArgsConstructor
|
|
public class RedisUtil {
|
|
|
|
private final RedisTemplate<String, String> redisTemplate;
|
|
|
|
public boolean set(String key, String value) {
|
|
redisTemplate.opsForValue().set(key, value);
|
|
return true;
|
|
}
|
|
|
|
public <V> boolean set(String key, V value) {
|
|
try {
|
|
set(key, ConvertUtil.toJsonStr(value));
|
|
} catch (JsonProcessingException e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public Optional<String> get(String key) {
|
|
return Optional.ofNullable(redisTemplate.opsForValue().get(key));
|
|
}
|
|
|
|
public <V> Optional<V> get(String key, Class<V> vClass) {
|
|
return get(key).map(s -> {
|
|
try {
|
|
return ConvertUtil.fromJsonStr(s, vClass);
|
|
} catch (JsonProcessingException e) {
|
|
return null;
|
|
}
|
|
});
|
|
}
|
|
|
|
public void delete(String key) {
|
|
redisTemplate.delete(key);
|
|
}
|
|
|
|
public boolean setex(String key, String value, long timeout) {
|
|
redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(timeout));
|
|
return true;
|
|
}
|
|
|
|
public <V> boolean setex(String key, V value, long timeout) {
|
|
try {
|
|
setex(key, ConvertUtil.toJsonStr(value), timeout);
|
|
} catch (JsonProcessingException e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public static String parseKey(String pattern, Object... args) {
|
|
return String.format(pattern, args);
|
|
}
|
|
|
|
}
|