redis作为缓存服务器

redis较于memcached缓存有数据结构多,运行速度快,数据可持久化等特点.作为nosql系列数据库的redis越来越受到项目的青睐。

在业务代码中添加缓存,我们的业务逻辑一般来说都是:从缓存中拿数据-->有的话直接返回-->没有的话查询数据库-->数据库中的结果保存到缓存当中。但是不管怎样,我们涉及到缓存的代码不能影响正常的业务逻辑。比如说从缓存中没查到数据,业务逻辑不能死掉了,所以一般都会Try{}catch(){}掉。撸一段代码。

public List<EasyUITreeNode> getContentCatList(long parentId) {
		// 添加缓存
		//1:从缓存中查询数据
		try {
			String json = jedisClient.hget("NodeList", parentId+"");
			if (StringUtils.isNotBlank(json)) {
				//2:缓存中存在直接返回
				List<EasyUITreeNode> jsonToList = JsonUtils.jsonToList(json, EasyUITreeNode.class);
				return jsonToList;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//3:缓存中没有从数据库查询
		TbContentCategoryExample example = new TbContentCategoryExample();
		Criteria criteria = example.createCriteria();
		// 设置条件
		criteria.andParentIdEqualTo(parentId);
		// 执行查询
		List<TbContentCategory> catList = contentCategoryMapper.selectByExample(example);
		
		List<EasyUITreeNode> nodeList = new ArrayList<EasyUITreeNode>();
		for (TbContentCategory tbContentCategory : catList) {
			EasyUITreeNode node = new EasyUITreeNode();
			node.setId(tbContentCategory.getId());
			node.setText(tbContentCategory.getName());
			node.setState(tbContentCategory.getIsParent()?"closed":"open");
			nodeList.add(node);
		}
		//4:数据库中查询后插入到缓存,返回结果
		try {
			jedisClient.hset("NodeList", parentId+"", JsonUtils.objectToJson(nodeList));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nodeList;
	}

以上就是在业务逻辑中添加缓存,但是有一个问题会影响到缓存准确度的问题,就是缓存同步,即缓存和数据库中的数据保持一致性。

多数情况下,添加,修改,删除这些改变数据库状态的操作会造成缓存不能同步的问题,所以我们在做这些操作的时候需要删除对应的缓存数据。为什么是删除呢?因为删除了缓存中的数据,下次执行查询的时候,缓存中没有,肯定直接从数据库中查询了,这时候拿到的是完整的数据,然后再同步到缓存中,这样我们保证数据一致性的目的就达到了。

over.

猜你喜欢

转载自blog.csdn.net/ylldl/article/details/81011903