博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring 的redis操作类RedisTemplate
阅读量:4572 次
发布时间:2019-06-08

本文共 2359 字,大约阅读时间需要 7 分钟。

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
redisTemplate(RedisConnectionFactory redisConnectionFactory) { Jackson2JsonRedisSerializer
jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisTemplate
template = new RedisTemplate
(); 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
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

你可能感兴趣的文章
redis 主从配置
查看>>
Centos 7.x 服务器部署常用命令
查看>>
Android开源实战:使用MVP+Retrofit开发一款文字阅读APP
查看>>
BZOJ4025 二分图 线段树分治、带权并查集
查看>>
[乐意黎原创] cuteftp 9 显示中文乱码
查看>>
操作MongoDB
查看>>
正则表达式 匹配中文 数字 字母 下划线
查看>>
TCP的状态迁移图
查看>>
统计连接到主机前十的ip地址和连接数
查看>>
第八周学习进度
查看>>
CopyUtils 讲一个对象的全部(或部分)属性值copy给另一个对象
查看>>
《局外人》豆瓣摘录
查看>>
数据库基础查询
查看>>
Eclipse安装SVN
查看>>
Linux性能优化建议
查看>>
OTL翻译(3) -- OTL的主要类
查看>>
java当中的定时器的4种使用方式
查看>>
hive
查看>>
Java集合排序(面试必考点之一)
查看>>
Tsql 获取服务器信息
查看>>