標籤:amt dao層 set map 自動 from jackson redist ash
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 RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(redisConnectionFactory); //安全執行緒的串連工程 template.setKeySerializer(jackson2JsonRedisSerializer); //key序列化方式採用fastJson template.setValueSerializer(jackson2JsonRedisSerializer); //value序列化方式 template.setHashKeySerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
這樣就可以在需要的時候直接使用自動注入(@Autowired)擷取redisTemplate操作redis了:
@Autowiredprivate RedisTemplate<String, String> redisTemplate;@Overridepublic 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);}
spring 的redis操作類RedisTemplate