Files
timeline-server/timeline-component-common/src/main/java/com/timeline/common/utils/RedisUtils.java
2025-12-24 14:14:59 +08:00

68 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}