spring 集成的redis操作几乎都在RedisTemplate内了。
已spring boot为例,
再properties属性文件内配置好
redis的参数
spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=redispassspring.redis.database=0spring.redis.timeout=5000
再到 Application启动类下加入以下代码:
@Bean public RedisTemplateredisTemplate(RedisConnectionFactory redisConnectionFactory) { Jackson2JsonRedisSerializer
这样就可以在需要的时候直接使用自动注入(@Autowired)获取redisTemplate操作redis了:
@Autowired private RedisTemplateredisTemplate; @Override public Result selectUserById(String id) { if(StringUtils.isEmpty(id)){ throw new BusinessException(CommonConstants.ErrorCode.ERROR_ILLEGAL_PARAMTER);//ID为空 } String redisCache = redisTemplate.opsForValue().get(CacheKeys.SELECT_USER_PHONE_KEYS+id); if(redisCache!=null){ Result result = new Gson().fromJson(redisCache, Result.class); if(result.getResult() == null){ throw new BusinessException(CommonConstants.ErrorCode.ERROR_ILLEGAL_USER);//用户不存在 } return result; } User selectByPrimaryKey = userMapper.selectByPrimaryKey(id); //自己项目的Dao层 redisTemplate.opsForValue().set(CacheKeys.SELECT_USER_PHONE_KEYS+id, CommonConstants.GSONIGNORENULL.toJson(new Result(selectByPrimaryKey)), 1, TimeUnit.HOURS); //缓存有效时间为1天 if(selectByPrimaryKey == null){ throw new BusinessException(CommonConstants.ErrorCode.ERROR_ILLEGAL_USER);//用户不存在 } return new Result(selectByPrimaryKey); }