springboot整合redis缓存的增删改查

 springboot整合redis缓存的增删改查_校草小阳的博客-CSDN博客

 一、Redis方法

@Autowired

private RedisTemplate redisTemplate;

 

// 判断当前key是否存在

redisTemplate.hasKey(key);

 

// 读取所有

redisTemplate.opsForList();

        // 写入缓存

        opsForList.leftPushAll(key, list)

 

// 读取缓存

redisTemplate.opsForValue().get(key);

 

// 写入缓存 (修改,新增)

redisTemplate.opsForValue().set(key, value);

 

// 更新缓存 (没有就添加,有就修改)

redisTemplate.opsForValue.getAndSet(key, value);

 

// 删除缓存

redisTemplate.delete(key);

 

// 设置过期时间   key相同就可以

 ①DAYS:天

 ②HOURS:小时

 ③MINUTES:分钟

 ④SECONDS:秒

 ⑤MILLISECONDS:毫秒

redisTemplate.opsForValue().set(key,value,30,TimeUnit.SECONDS);

 

Redis配置  

防止乱码

@Configuration
@SuppressWarnings("all")
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
    @Bean
    RedisCacheWriter writer(RedisTemplate redisTemplate) {
        return RedisCacheWriter.nonLockingRedisCacheWriter(Objects.requireNonNull(redisTemplate.getConnectionFactory()));
    }

    @Bean
    CacheManager cacheManager(RedisCacheWriter writer) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        Map configurationMap = new HashMap<>();

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1))//time
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        //此处可以自定义缓存空间的缓存的过期时间,可以根据自己实际情况进行设置,也可以不设置,用统一过期时间
        configurationMap.put("test-controller", config.entryTtl(Duration.ofSeconds(200)));

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        return RedisCacheManager.builder(writer)
                .initialCacheNames(configurationMap.keySet())
                .withInitialCacheConfigurations(configurationMap)
                //其他缓存空间缓存过期时间为500S
                .cacheDefaults(config.entryTtl(Duration.ofSeconds(500)))
                .build();
    }

 

Cache

Springboot中cache的使用_苏灿,月色真美的博客-CSDN博客_cache springboot

@Cacheable :缓存数据
@CachePut : 更新缓存的数据
@CacheEvict : 删除缓存的数据

 // @Cacheable缓存key为name的数据到缓存usercache中
@Cacheable(cacheNames   = "usercache", key = "#id")
    public User findUser(Integer id) {
        System.out.println("无缓存时执行下面代码,获取zhangsan,Time:" + new Date().getSeconds());
        return userDao.findById(id);
    }

 

 

你可能感兴趣的:(java,spring,boot,redis,数据库)