用Redis实现缓存以及缓存同步

版权声明: https://blog.csdn.net/pbrlovejava/article/details/82050033

使用Redis做缓存的大体思路:在相应的数据获取层,将获取到的数据存储一份到Redis中,在下次请求该数据之前,先在Redis中搜索该数据并提取出来,实现缓存的快速读取。

1、传统开发模式:多次请求数据库,数据库压力高,系统响应慢

2、使用Redis做缓存的开发模式:首次请求数据库,并将数据存入Redis中实现缓存,短时间内再次读取时只需从缓存中获取,大大减少数据库压力和提高响应速度

 

 3、具体代码实现也十分简单(在使用Redis之前需要在服务器中搭建Redis,并在spring中注册Jedis,具体不再赘述):

/**
	 * 查询内容
	 */
	@Override
	public List<TbContent> findContent(Long CATAGORY_LUNBO_ID) {
		String cid = CATAGORY_LUNBO_ID.toString();
		
		//查询到缓存
		try {
			String content_lunbo_string = jedisClient.hget(CONTENT_LUNBO,cid);
			if(StringUtils.isNotBlank(content_lunbo_string)){
		 		//缓存存在
		 		//转化为相应的list
				List<TbContent> contentList = JsonUtils.jsonToList(content_lunbo_string, TbContent.class);
				return contentList;
		 	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		 	
			//查询不到该缓存,查询数据库
			TbContentExample example = new TbContentExample();
			com.iteason.pojo.TbContentExample.Criteria criteria = example.createCriteria();
			//设置条件
			criteria.andCategoryIdEqualTo(CATAGORY_LUNBO_ID);
			List<TbContent> contentList = tbContentMapper.selectByExample(example);
			
			
			//添加list转化为json到缓存中
			String contentJson = JsonUtils.objectToJson(contentList);
			//添加hash缓存格式为:key filed value
			try {
				jedisClient.hset(CONTENT_LUNBO,cid, contentJson);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		 
			return contentList;
	
		
	}

4、实现缓存的同步:在每次更新数据后,如果上次的缓存数据仍保留着,那么在查询时依然会读取到缓存中的旧数据,这时候需要实现缓存同步,最简单的做法就是在每次更新操作后,删去该数据的缓存,让下一次访问时找不到该缓存,从而读取数据库中的实时数据

猜你喜欢

转载自blog.csdn.net/pbrlovejava/article/details/82050033