spring 的redis操作類RedisTemplate

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.