对象缓存到redis
@Autowired
private StringRedisTemplate stringRedisTemplate;
public SeckillUser getSeckillUser(long id) { //查redis缓存 String seckillGoods = stringRedisTemplate.opsForValue().get(SeckillUserKey.seckillUserKey.getPrefix() + id); if(!StringUtils.isEmpty(seckillGoods)){ //如果不为空,把字符串转换成对象返回 SeckillUser seckillUser = JSON.parseObject(seckillGoods, SeckillUser.class); return seckillUser; } //如果redis里面没有,就从数据库查 SeckillUser seckillUser = seckUserMapper.selectById(id); //如果数据库里查出来了,就转换成json字符串添加到redis里 if(seckillUser!=null){ String seckillUserjson = JSON.toJSONString(seckillUser); stringRedisTemplate.opsForValue().set(SeckillUserKey.seckillUserKey.getPrefix() + id,seckillUserjson); } return seckillUser; }