spring 的redis操作类RedisTemplate

spring 集成的redis操作几乎都在RedisTemplate内了。

已spring boot为例,

再properties属性文件内配置好

redis的参数

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);
	}

  




转载于:https://www.cnblogs.com/tietazhan/p/7479585.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值