spring 的redis操做類RedisTemplate

spring 集成的redis操做幾乎都在RedisTemplate內了。html

已spring boot爲例,java

再properties屬性文件內配置好redis

redis的參數spring

spring.redis.host=127.0.0.1 
spring.redis.port=6379  
spring.redis.password=redispass
spring.redis.database=0
spring.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了:安全

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@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);
	}
相關文章
相關標籤/搜索