虽然springboot有提供一些封装好的redis 但有一些复制的情景还是得用RedisTemplate来解决.
首先是redisConfig 注册与实现 复制黏贴
@Component public class RedisCacheConfig { @Bean public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory redisConnectionFactory) { Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer = initFactory(); RedisTemplate<String, ?> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(jackson2JsonRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } private Jackson2JsonRedisSerializer<Object> initFactory() { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(om); return jackson2JsonRedisSerializer; } private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() { Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(0); //1小时有效期 redisCacheConfigurationMap.put("countPoiInfo", this.getRedisCacheConfigurationWithTtl(60 * 60)); return redisCacheConfigurationMap; } private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = initFactory(); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); redisCacheConfiguration = redisCacheConfiguration .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .entryTtl(Duration.ofSeconds(seconds)); return redisCacheConfiguration; } }
在类中使用, 先注入(前面配置类中有注册了这个bean)再使用
@Resource private RedisTemplate redisTemplate;
举个例子对应@Cacheable的就是hash类型.
HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
三个泛型对应@Cacheable属性
hash | @Cacheable |
---|---|
第一个String | value |
第二个String | key |
第三个为Object | 缓存的数据 |
//获取数据 Object cacheValue = hashOperations.get(hashKey, key); //获取hashKey下所有的键值对 Set<Map.Entry<String, Integer>> entries = hashOperations.entries(hashKey).entrySet(); //放入数据 hashOperations.put(hashKey,key, newValue); //删除数据 hashOperations.delete(hashKey, key);