redis 存放 redis 不同list集合 不同对象取值 list集合
测试代码
List < User > userList= new ArrayList < > ( ) ; userList= ArrayListConstants . getUserSql; RedisTemplateUtil . setRedisList ( "keyredis" , userList) ; 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 ;
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 ; } }
}