Redis缓存预热

概述

在秒杀开始前通常要进行将数据加载到缓存中,也叫缓存预热

demo

Redis序列化配置,通常有两种方式,通过配置类进行序列化配置,

@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory factory;

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

}

通过PostConstruct进行序列化配置

@Autowired
    private RedisTemplate<String,String> redisTemplate;

    @PostConstruct
    public void init() {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        redisTemplate.setHashValueSerializer(redisSerializer);
    }

通常推荐第一种,全局的序列化配置,只需要配置一次即可在任何地方使用,第二种则是出现RedisTeplate的地方都要配置一次init中的代码

缓存预热类,实现ApplicationRunner接口,在程序启动时的时候就会加载该类,将数据写入Redis中,即可实现缓存预热

@Component
public class RedisPreHeat implements ApplicationRunner {

    @Autowired
    private IStockService iStockService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {

       Stock stock =
               iStockService.getOne(new QueryWrapper<Stock>().lambda().eq(Stock::getProductId,9));

       redisTemplate.delete("Stock:Pre:Hot");

       redisTemplate.opsForValue().set("Stock:Pre:Hot",String.valueOf(stock.getCount()));

    }
}

数据库信息如下:
Redis缓存预热_第1张图片

数据库中数据与缓存中数据保存一直的话,可以考虑定时任务获取缓存中的数据更新到mysql中,往后再做实现

你可能感兴趣的:(redis,缓存,redis,java)