工具类
package org.springblade.questionnaire.redis;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
// 存储对象到Redis
public void setObjectToRedis(String key, Object obj) {
try {
// 将对象序列化为JSON字符串
String value = objectMapper.writeValueAsString(obj);
// 使用StringRedisTemplate将JSON字符串存储到Redis
stringRedisTemplate.opsForValue().set(key, value);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize object to JSON", e);
}
}
// 从Redis获取对象
public <T> T getObjectFromRedis(String key, Class<T> clazz) {
String json = stringRedisTemplate.opsForValue().get(key);
if (json != null) {
try {
// 将JSON字符串反序列化为对象
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize JSON to object", e);
}
}
return null;
}
// 存储对象数组到Redis
public <T> void setArrayToRedis(String key, T[] array) {
try {
// 将对象数组序列化为JSON字符串
String value = objectMapper.writeValueAsString(array);
// 使用StringRedisTemplate将JSON字符串存储到Redis
stringRedisTemplate.opsForValue().set(key, value);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize object array to JSON", e);
}
}
// 从Redis获取对象数组
@SuppressWarnings("unchecked")
public <T> T[] getArrayFromRedis(String key, Class<T[]> clazz) {
String json = stringRedisTemplate.opsForValue().get(key);
if (json != null) {
try {
// 将JSON字符串反序列化为对象数组
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize JSON to object array", e);
}
}
return null;
}
// 存储对象到Redis并设置过期时间
public void setObjectToRedisWithTime(String key, Object obj, long timeout, TimeUnit timeUnit) {
try {
// 将对象序列化为JSON字符串
String value = objectMapper.writeValueAsString(obj);
// 使用StringRedisTemplate将JSON字符串存储到Redis并设置过期时间
stringRedisTemplate.opsForValue().set(key, value, timeout, timeUnit);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize object to JSON", e);
}
}
// 存储对象数组到Redis并设置过期时间
public <T> void setArrayToRedisWithTime(String key, T[] array, long timeout, TimeUnit timeUnit) {
try {
// 将对象数组序列化为JSON字符串
String value = objectMapper.writeValueAsString(array);
// 使用StringRedisTemplate将JSON字符串存储到Redis并设置过期时间
stringRedisTemplate.opsForValue().set(key, value, timeout, timeUnit);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize object array to JSON", e);
}
}
// 存储字符串到Redis并设置过期时间
public void setStringToRedis(String key, String value, long timeout, TimeUnit timeUnit) {
// 使用StringRedisTemplate将字符串存储到Redis并设置过期时间
stringRedisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
// 从Redis获取字符串
public String getStringFromRedis(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
// 存储 Map<String, Map<String, String>> 到 Redis 并设置过期时间
public void setTranslationsToRedis(String key, Map<String, Map<String, String>> translations, long timeout, TimeUnit timeUnit) {
try {
// 将 Map 序列化为 JSON 字符串
String value = objectMapper.writeValueAsString(translations);
// 使用 StringRedisTemplate 将 JSON 字符串存储到 Redis 并设置过期时间
stringRedisTemplate.opsForValue().set(key, value, timeout, timeUnit);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize translations map to JSON", e);
}
}
// 从 Redis 获取 Map<String, Map<String, String>>
public Map<String, Map<String, String>> getTranslationsFromRedis(String key) {
String json = stringRedisTemplate.opsForValue().get(key);
if (json != null) {
try {
// 将 JSON 字符串反序列化为 Map<String, Map<String, String>>
return objectMapper.readValue(json, new TypeReference<Map<String, Map<String, String>>>() {});
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize JSON to translations map", e);
}
}
return null;
}
/**
* 增加计数器的值并返回新的计数值。
* 如果计数器不存在,则初始化为1。
*
* @param key 计数器的键名
* @param expireTime 过期时间(如果计数器是新创建的)
* @param timeUnit 时间单位
* @return 新的计数值
*/
public long incrementCounter(String key, long expireTime, TimeUnit timeUnit) {
Long count = stringRedisTemplate.opsForValue().increment(key, 1);
if (count == 1) { // 如果是第一次设置,则设置过期时间为指定的时间
stringRedisTemplate.expire(key, expireTime, timeUnit);
}
return count;
}
/**
* 获取计数器的当前值。
*
* @param key 计数器的键名
* @return 当前计数值,如果不存在则返回0
*/
public long getCounterValue(String key) {
String value = stringRedisTemplate.opsForValue().get(key);
return value != null ? Long.parseLong(value) : 0;
}
/**
* 设置计数器的值并设置过期时间。
*
* @param key 计数器的键名
* @param value 计数值
* @param expireTime 过期时间
* @param timeUnit 时间单位
*/
public void setCounterValue(String key, long value, long expireTime, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
stringRedisTemplate.expire(key, expireTime, timeUnit);
}
/**
* 检查并限制计数器的值不超过最大值。
* 如果超过了最大值,则抛出异常。
*
* @param key 计数器的键名
* @param maxValue 最大允许的计数值
* @param errorMessage 超过最大值时的错误消息
*/
public void checkCounterLimit(String key, int maxValue, String errorMessage) {
long count = getCounterValue(key);
if (count > maxValue) {
throw new RuntimeException(errorMessage);
}
}
}
引用
@Autowired
private RedisService redisService;
调用方法
一般设置过期时间一天,看情况而定
//存入redis,verificationCode
redisService.setStringToRedis(userMail + ":content", verificationCode, 3600, TimeUnit.SECONDS);
// 检查并限制计数器
redisService.checkCounterLimit(userMail + ":count", 10, "今日验证码发送次数已达上限,请明日再试!");
// 增加计数器的值
long newCount = redisService.incrementCounter(userMail + ":count", 1, TimeUnit.DAYS);
System.out.println("newCount==="+newCount);