redis 存放 redis 不同list集合 不同对象取值 list集合
测试代码
List<User> userList= new ArrayList<>();
userList= ArrayListConstants.getUserSql;//查询 list 集合数据
RedisTemplateUtil.setRedisList("keyredis", userList);//set 集合数据
RedisTemplateUtil.getRedisList("keyredis", User.class);//取集合数据
GenericTypeReference.java
import com.fasterxml.jackson.core.type.TypeReference;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import java.lang.reflect.Type;
import java.util.List;
/**
* @Author
* @Data 2024-04-12 10:37:03
*/
public class GenericTypeReference<T> extends TypeReference<List<T>> {
private final Class<T> elementType;
public GenericTypeReference(Class<T> elementType) {
this.elementType = elementType;
}
@Override
public Type getType() {
return ParameterizedTypeImpl.make(List.class, new Type[]{elementType}, null);
}
}
RedisTemplateUtil 方法
public class RedisTemplateUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static RedisTemplate redisTemplates;
public static <T> void setRedisList(String key, List<T> list) {
try {
String value = objectMapper.writeValueAsString(list);
redisTemplates.opsForValue().set(key, value);
} catch (JsonProcessingException e) {
logger.error("redis赋值list集合方法:setRedisList 报错" + e.getMessage());
}
}
public static <T> List<T> getRedisList(String key, Class<T> elementType) {
try {
String json = (String) redisTemplates.opsForValue().get(key);
return objectMapper.readValue(json, new GenericTypeReference<>(elementType));
} catch (JsonProcessingException e) {
logger.error("redis取list集合方法:getRedisList 报错" + e.getMessage());
return null;
}
}
public static void setRedisMapList(String key, List<Map<String, Object>> mapList) {
try {
String value = objectMapper.writeValueAsString(mapList);
redisTemplates.opsForValue().set(key, value);
} catch (JsonProcessingException e) {
logger.error("redis赋值list集合方法:setRedisMapList 报错" + e.getMessage());
}
}
public static List<Map<String, Object>> getRedisMapList(String key) {
try {
String json = (String) redisTemplates.opsForValue().get(key);
return objectMapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {
});
} catch (JsonProcessingException e) {
logger.error("redis取list集合方法:getRedisMapList 报错" + e.getMessage());
return null;
}
}
}
文章来源地址https://www.toymoban.com/news/detail-852853.html
文章来源:https://www.toymoban.com/news/detail-852853.html
到了这里,关于redis 存放 redis 不同list集合 不同对象取值 list集合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!