redis 优化数据库
2018-02-07 21:29
183 查看
需求:给用户分配管理权限时,每次回显权限树的列表时,都要查询数据库,,,这样会找出数据库压力增大,影响性能,我们可以使用redis 缓存数据 ,,,,把数据缓存到redis中,这样下次查看数据时就不用查询数据库了。直接在redis中拿到, 这样优化了程序性能。
//根据applicationContext-redis配置文件,加载文件 看下图 @Autowired private JedisPool pool; //ajax 回显数据 @Action(value="roleAction_genzTreeNodes") public String genzTreeNodes() throws IOException{ //通过ID查询数据库,获取数据 Role role = RoleService.get(model.getId()); //获取jedis Jedis jedis = pool.getResource(); //通过jedis,获取里面的ID String returnJedis = jedis.get(role.getId()); //判断ID返回值是否为空。不为空说明有数据,直接通过JSON传到页面 // 为空说明没有数据,查询数据库获取数据 if(UtilFuns.isEmpty(returnJedis)){ Set<Module> modules = role.getModules(); Specification<Module> spec = new Specification<Module>() { public Predicate toPredicate(Root<Module> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // TODO Auto-generated method stub return cb.equal(root.get("state").as(Integer.class), 1); } }; List<Module> find = moduleService.find(spec); System.out.println("111111111111"+find); //[{"id": "11","pId": "1","name": "随意勾选 1-1"}, {"id": "111","pId": "11","name": "随意勾选 1-1-1","checked": "true"}] ArrayList<Map> list = new ArrayList<>(); for (Module module : find) { HashMap map = new HashMap(); map.put("id", module.getId()); map.put("pId", module.getParentId()); map.put("name", module.getName()); if(modules.contains(module)){ map.put("checked", true); } list.add(map); returnJedis= JSON.toJSONString(list); //将从数据库查询到的数据ID传给redis 这样下次查看的时候就不用再数据库查询了。直接在redis中查 jedis.set(role.getId(), returnJedis); } System.out.println("数据库获取数据"); }else{ System.out.println("redis获取数据"); } HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); response.getWriter().write(returnJedis); return NONE; } //如果数据需要修改,或者更改数据时,在更改后,一定注意要清空redis 否则或找出数据内容不匹配 //Jedis jedis = pool.getResource(); //jedis.del(role.getId());
相关文章推荐
- NoSQL数据库:Redis内存使用优化与存储
- nosql类型的数据库:mongodb、Redis、Memcached的优化点
- NoSQL数据库:Redis内存使用优化与存储
- NoSQL数据库:Redis内存使用优化与存储
- NoSQL数据库:Redis内存使用优化与存储
- java(优化25) Redis缓存加索引处理数据库百万级并发的方案
- 程序对批量数据写入数据库的优化--引入Redis并通过定时器来触发
- 程序对批量数据写入数据库的优化--引入Redis并通过定时器来触发
- Python学习之使用Python操作Redis数据库
- 面向程序员的数据库访问性能优化法则
- 优化 shiro 多次调用 redis 的问题
- 数据库优化之表结构优化
- 大数据量数据库设计与优化方案 - 转
- 一次数据库的简单性能优化
- 面向程序员的数据库访问性能优化法则
- 高性能NOSQL数据库redis结合谷歌开源tcmalloc库的安装笔记
- MySQL百万级数据库查询优化技巧
- 数据库的优化
- 使用“数据库引擎优化顾问”来构建正确的索引设计
- Oracle优化 latch free问题Result Cache:RC Latch引起数据库缓慢