项目部署演示:
需求分析:网站的首页访问量大,每次访问都需要查询数据库获取数据回显,如果访问量一旦偏大,就会出现高并发,以及数据库崩溃,为了解决这个问题,在项目开发中可以搭建一个redis服务器,用来缓存数据,当第一次访问数据库时,把数据传到redis中,用户访问页面时从redis中获取数据解决数据库的压力,当我们修改,删除,增加数据库内容是,我们情况redis缓存 ,这样就可以保证redis与数据库数据同步了
代码实现:
一:配置项目文件,
(1).引入依赖,在我们的公共集群中配置 pom.xml 映入依赖 (因为缓存对于我们整个的系统来说是通用功能。广告需要用,其它数据可能也会用到,所以 我们将配置放在公共组件层(pinyougou-common)中较为合理。 )
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
(2)创建配置文件
将资源中的redis-config.properties 和applicationContext-redis.xml 拷贝至pinyougou-common
(3)pinyougou-content-service 依赖 pinyougou-common
二,后端服务实现层 service(其他的层和直接查询数据库获取数据一样的操作)
1.查询操作,用户访问页面
//注入redis模版对象 //contentMapper 是我的一个到对象
@Autowired
private RedisTemplate redisTemplate;
public List<TbContent> findContentCategoryId(Long categoryId) {
try {
//先查询缓存
List<TbContent> adList = (List<TbContent>) redisTemplate.boundHashOps("index_cache").get(categoryId+"");
//判断缓存数据是否存在
if(adList!=null && adList.size()>0){
System.out.println("redis中获取数据");
return adList;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建广告内容表example对象
TbContentExample example = new TbContentExample();
// 创建criteria对象
Criteria createCriteria = example.createCriteria();
// 设置查询参数
// 外键
createCriteria.andCategoryIdEqualTo(categoryId);
// 查询有效广告
createCriteria.andStatusEqualTo("1");
// 设置排序字段
example.setOrderByClause("sort_order");
//执行查询
List<TbContent> list = contentMapper.selectByExample(example);
//添加缓存数据
redisTemplate.boundHashOps("index_cache").put(categoryId+"",list);
return list;
}
2.增 删 改 的操作 在操作后情况redis数据库
//新增时 在我们操作完数据库后直接情况redis即可
//清空缓存
redisTemplate.boundHashOps("index_cache").delete(tbContent.getCategoryId()+"");
但是在修改,删除时 由于可能会发生修改删除ID的情况 我们应先查询到对象数据再在其删除 修改后情况redis数据库
/**
* 修改
* 1,分类id也发生了变化
* 2,id没法发生变化
* contentMapper 是我的一个到对象
*/
@Override
public void update(TbContent content) {
//根据当前id查询广告对象
TbContent tbContent = contentMapper.selectByPrimaryKey(content.getId());
//清空缓存
redisTemplate.boundHashOps("index_cache").delete(tbContent.getCategoryId()+"");
contentMapper.updateByPrimaryKey(content);
}