common工程增加Redis工具

This commit is contained in:
jiangh277
2025-12-24 14:14:59 +08:00
parent aa42f35254
commit 3eb445291f
3 changed files with 134 additions and 2 deletions

View File

@@ -0,0 +1,67 @@
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);
}
}