68 lines
2.0 KiB
Java
68 lines
2.0 KiB
Java
|
|
package com.timeline.common.utils;
|
|||
|
|
|
|||
|
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
|||
|
|
import org.springframework.lang.NonNull;
|
|||
|
|
import org.springframework.stereotype.Component;
|
|||
|
|
|
|||
|
|
import java.time.Duration;
|
|||
|
|
import java.util.concurrent.TimeUnit;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Redis 公共工具:基于 StringRedisTemplate 的常用操作封装。
|
|||
|
|
*/
|
|||
|
|
@Component
|
|||
|
|
public class RedisUtils {
|
|||
|
|
|
|||
|
|
private final StringRedisTemplate stringRedisTemplate;
|
|||
|
|
|
|||
|
|
public RedisUtils(StringRedisTemplate stringRedisTemplate) {
|
|||
|
|
this.stringRedisTemplate = stringRedisTemplate;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 设置值(无过期时间) */
|
|||
|
|
public void set(@NonNull String key, @NonNull String value) {
|
|||
|
|
stringRedisTemplate.opsForValue().set(key, value);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 设置值并指定过期(毫秒) */
|
|||
|
|
public void set(@NonNull String key, @NonNull String value, long timeoutMs) {
|
|||
|
|
stringRedisTemplate.opsForValue().set(key, value, timeoutMs, TimeUnit.MILLISECONDS);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 设置值并指定过期(Duration) */
|
|||
|
|
public void set(@NonNull String key, @NonNull String value, @NonNull Duration ttl) {
|
|||
|
|
stringRedisTemplate.opsForValue().set(key, value, ttl);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 获取值 */
|
|||
|
|
public String get(@NonNull String key) {
|
|||
|
|
return stringRedisTemplate.opsForValue().get(key);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 删除键 */
|
|||
|
|
public Boolean del(@NonNull String key) {
|
|||
|
|
return stringRedisTemplate.delete(key);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 自增 */
|
|||
|
|
public Long incr(@NonNull String key) {
|
|||
|
|
return stringRedisTemplate.opsForValue().increment(key);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 自减 */
|
|||
|
|
public Long decr(@NonNull String key) {
|
|||
|
|
return stringRedisTemplate.opsForValue().decrement(key);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 设置过期(秒) */
|
|||
|
|
public Boolean expire(@NonNull String key, long seconds) {
|
|||
|
|
return stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 判断键是否存在 */
|
|||
|
|
public Boolean hasKey(@NonNull String key) {
|
|||
|
|
return stringRedisTemplate.hasKey(key);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|