1. SpringDataRedis简介

1.1项目常见问题思考

我们目前的系统已经实现了广告后台管理和广告前台展示,但是对于首页每天有大量的人访问,对数据库造成很大的访问压力,甚至是瘫痪。那如何解决呢?我们通常的做法有两种:一种是数据缓存、一种是网页静态化。我们今天讨论第一种解决方案。

1.2 Redis

redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写。企业开发通常采用Redis来实现缓存。同类的产品还有memcache 、memcached 、MongoDB等。

1.3 Jedis

Jedis是Redis官方推出的一款面向Java的客户端,提供了很多接口供Java语言调用。可以在Redis官网下载,当然还有一些开源爱好者提供的客户端,如Jredis、SRP等等,推荐使用Jedis。

1.4 Spring Data Redis

Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis,  JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

spring-data-redis针对jedis提供了如下功能:
         1、连接池自动管理,提供了一个高度封装的“RedisTemplate”类
         2、针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
             ValueOperations:简单K-V操作
             SetOperations:set类型数据操作
             ZSetOperations:zset类型数据操作
             HashOperations:针对map类型的数据操作
             ListOperations:针对list类型的数据操作

1.5
Spring Data Redis入门小Demo

1.5.1准备工作

(1)构建Maven工程  SpringDataRedisDemo

(2)引入Spring相关依赖、引入JUnit依赖

(3)引入Jedis和SpringDataRedis依赖

<!-- 缓存 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>

(4)在src/main/resources下创建properties文件夹,建立redis-config.properties

# Redis settings
redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.database=0
# 最大空闲数
redis.maxIdle=300
# 连接时的最大等待毫秒数
redis.maxWait=3000
# 在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的
redis.testOnBorrow=true

在src/main/resources下创建spring文件夹 ,创建applicationContext-redis.xml

<context:property-placeholder location="classpath*:properties/*.properties" />
<!-- redis 相关配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="JedisConnectionFactory" />
</bean>

maxIdle :最大空闲数

maxWaitMillis:连接时的最大等待毫秒数

testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的;

1.5.2 值类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestValue {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void setValue(){
redisTemplate.boundValueOps("name").set("itcast");
}
@Test
public void getValue(){
String str = (String) redisTemplate.boundValueOps("name").get();
System.out.println(str);
}
@Test
public void deleteValue(){
redisTemplate.delete("name");;
}
}

1.5.3 Set类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestSet { @Autowired
private RedisTemplate redisTemplate; /**
* 存入值
*/
@Test
public void setValue(){
redisTemplate.boundSetOps("nameset").add("曹操");
redisTemplate.boundSetOps("nameset").add("刘备");
redisTemplate.boundSetOps("nameset").add("孙权");
} /**
* 提取值
*/
@Test
public void getValue(){
Set members = redisTemplate.boundSetOps("nameset").members();
System.out.println(members);
} /**
* 删除集合中的某一个值
*/
@Test
public void deleteValue(){
redisTemplate.boundSetOps("nameset").remove("孙权");
} /**
* 删除整个集合
*/
@Test
public void deleteAllValue(){
redisTemplate.delete("nameset");
}
}

1.5.4 List类型操作

(1)右压栈

  /**
* 右压栈:后添加的对象排在后边
*/
@Test
public void testSetValue1(){
redisTemplate.boundListOps("namelist1").rightPush("刘备");
redisTemplate.boundListOps("namelist1").rightPush("关羽");
redisTemplate.boundListOps("namelist1").rightPush("张飞");
} /**
* 显示右压栈集合
*/
@Test
public void testGetValue1(){
List list = redisTemplate.boundListOps("namelist1").range(0, 10);
System.out.println(list);
}

运行结果: [刘备, 关羽, 张飞]

(2)左压栈

  /**
* 左压栈:后添加的对象排在前边
*/
@Test
public void testSetValue2(){
redisTemplate.boundListOps("namelist2").leftPush("刘备");
redisTemplate.boundListOps("namelist2").leftPush("关羽");
redisTemplate.boundListOps("namelist2").leftPush("张飞");
} /**
* 显示左压栈集合
*/
@Test
public void testGetValue2(){
List list = redisTemplate.boundListOps("namelist2").range(0, 10);
System.out.println(list);
}

运行结果:[张飞, 关羽, 刘备]

(3)根据索引查询元素

  /**
* 查询集合某个元素
*/
@Test
public void testSearchByIndex(){
String s = (String) redisTemplate.boundListOps("namelist1").index(1);
System.out.println(s);
}

(4)移除某个元素的值

  /**
* 移除集合某个元素
*/
@Test
public void testRemoveByIndex(){
redisTemplate.boundListOps("namelist1").remove(1, "关羽");
}

1.5.5 Hash类型操作

(1)存入值

@Test
public void testSetValue(){
redisTemplate.boundHashOps("namehash").put("a", "唐僧");
redisTemplate.boundHashOps("namehash").put("b", "悟空");
redisTemplate.boundHashOps("namehash").put("c", "八戒");
redisTemplate.boundHashOps("namehash").put("d", "沙僧");
}

(2)提取所有的KEY

@Test
public void testGetKeys(){
Set s = redisTemplate.boundHashOps("namehash").keys();
System.out.println(s);
}

运行结果:[a, b, c, d]

(3)提取所有的值

@Test
public void testGetValues(){
List values = redisTemplate.boundHashOps("namehash").values();
System.out.println(values);
}

运行结果:[唐僧, 悟空, 八戒, 沙僧]

(4)根据KEY提取值

@Test
public void testGetValueByKey(){
Object object = redisTemplate.boundHashOps("namehash").get("b");
System.out.println(object);
}

运行结果:悟空

(5)根据KEY移除值

@Test
public void testRemoveValueByKey(){
redisTemplate.boundHashOps("namehash").delete("c");
}

运行后再次查看集合内容:[唐僧, 悟空, 沙僧]

2. 网站首页轮播图显示-缓存广告数据

2.1 需求分析

  现在我们首页的广告每次都是从数据库读取,这样当网站访问量达到高峰时段,对数据库压力很大,并且影响执行效率。我们需要将这部分广告数据缓存起来。

2.2 读取缓存

2.2.1公共组件层

  添加缓存(添加图片 首页的轮播图,轮播图属于内容content), 推荐添加到服务层 taotao-content-Service 工程中。

  添加如下坐标到taotao-content-service中的pom.xml文件中:

     <!-- 缓存 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>

(2)创建配置文件:

  taotao-content-service 中创建 redis-config.properties 、applicationContext-redis.xml

2.2.2 后端服务实现层

  在 ContentServiceImpl 实现类中的 getContentListByCatId方法(查询内容列表)添加缓存:

    //////////根据cid查询内容列表
@Override
public List<TbContent> getContentListByCatId(long cid) {
List<TbContent> contentList= (List<TbContent>) redisTemplate.boundHashOps("content").get(cid);
if(contentList==null){
System.out.println("从数据库读取数据放入缓存");
//根据广告分类ID查询广告列表
TbContentExample example=new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(cid);
contentList = contentMapper.selectByExample(example);//执行查询,获取广告列表
//存入缓存
redisTemplate.boundHashOps("content").put(cid, contentList);
}else{
System.out.println("从缓存读取数据");
}
return contentList;
}

2.3 更新缓存

当广告数据发生变更时,需要将缓存数据清除,这样再次查询才能获取最新的数据

2.3.1 新增广告后清除缓存

修改在 ContentServiceImpl 实现类中的 addContent方法(添加内容):

///////////添加内容
@Override
public TaotaoResult addContent(TbContent content) {
//补全属性
content.setCreated(new Date());
content.setUpdated(new Date());
//插入数据
contentMapper.insert(content); //当添加内容的时候,需要清空此内容所属的分类下的所有的缓存
redisTemplate.boundHashOps("content").delete(content.getCategoryId()); //返回结果
return TaotaoResult.ok();
}

2.3.2 修改内容后清除缓存

修改在 ContentServiceImpl 实现类中的 editContent方法(编辑内容):

///////////编辑内容
@Override
public TaotaoResult editContent(TbContent content) { //**********************查询修改前的分类Id
Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
redisTemplate.boundHashOps("content").delete(categoryId); //补全属性
content.setCreated(new Date());
content.setUpdated(new Date());
//更新
contentMapper.updateByPrimaryKey(content); //*********************如果分类ID发生了修改,清除修改后的分类ID的缓存
if(categoryId.longValue()!=content.getCategoryId().longValue()){
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
} //返回结果
return TaotaoResult.ok();
}

2.3.3删除内容后清除缓存

//////////批量删除内容
@Override
public TaotaoResult deleteContent(List<Long> ids) { for(Long id:ids){
//*********************清除缓存
Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();//广告分类ID
redisTemplate.boundHashOps("content").delete(categoryId); contentMapper.deleteByPrimaryKey(id);
}
return TaotaoResult.ok();
}

redis缓存使用SpringDataRedis的更多相关文章

  1. spring-data-redis的使用/redis缓存

    1.导入依赖 <properties> <junit.version>4.12</junit.version> <spring.version>4.2. ...

  2. ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存

    基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...

  3. Redis 缓存 + Spring 的集成示例(转)

    <整合 spring 4(包括mvc.context.orm) + mybatis 3 示例>一文简要介绍了最新版本的 Spring MVC.IOC.MyBatis ORM 三者的整合以及 ...

  4. Spring+Redis的部署与Redis缓存使用示例

    由于项目的业务需要,这两天折腾了一下Spring-redis配置,有了前面用Spring托管hibernate的经验,这次可以说是顺风顺水,大概说一下流程. ubuntu 安装 redis sudo ...

  5. spring-boot的spring-cache中的扩展redis缓存的ttl和key名

    原文地址:spring-boot的spring-cache中的扩展redis缓存的ttl和key名 前提 spring-cache大家都用过,其中使用redis-cache大家也用过,至于如何使用怎么 ...

  6. Redis 缓存 + Spring 的集成示例(转载)

    1. 依赖包安装 pom.xml 加入: <dependency> <groupId>org.springframework.data</groupId> < ...

  7. 使用方法拦截机制在不修改原逻辑基础上为 spring MVC 工程添加 Redis 缓存

    首先,相关文件:链接: https://pan.baidu.com/s/1H-D2M4RfXWnKzNLmsbqiQQ 密码: 5dzk 文件说明: redis-2.4.5-win32-win64.z ...

  8. Redis缓存方案

    1 Redis简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis的开发 ...

  9. 使用maven简单搭建Spring mvc + redis缓存

    注:此文参考并整合了网上的文章 <spring缓存机制>:http://blog.csdn.net/sidongxue2/article/details/30516141 <配置 S ...

随机推荐

  1. mysql事务控制和锁定语句

    MySQL 支持对 MyISAM 和 MEMORY 存储引擎的表进行表级锁定,对 BDB 存储引擎的表进行页级锁定,对 InnoDB 存储引擎的表进行行级锁定.默认情况下,表锁和行锁都是自动获得的,不 ...

  2. 0506static【重点】

    static[重点] [重点] 1.[没有对象] [没有对象] [没有对象] 2.static 修饰的是一个资源共享类型的变量 3.静态成员变量的基本使用规范 static修饰的成员变量只能通过静态方 ...

  3. [jQuery插件]手写一个图片懒加载实现

    教你做图片懒加载插件 那一年 那一年,我还年轻 刚接手一个ASP.NET MVC 的 web 项目, (C#/jQuery/Bootstrap) 并没有做 web 的经验,没有预留学习时间, (作为项 ...

  4. [PHP学习教程 - 网络]004.模拟发送HTTP请求[GET/POST](HTTP Simulator)

    引言:经常在开发期间,客户端与服务端的调试都是借助于真实的容器返回.尤其是在处理到POST时,通常刚刚入门的兄弟姐妹就一定要借助容器.今天,我们就来处理一下模拟HTTP. 本文列举了常见的四种请求方式 ...

  5. Postgre数据库自定义函数

    自定函数 1.查询函数: select prosrc from pg_proc where proname='test' 参数说明 : test 为函数名. 2.删除函数: drop function ...

  6. Mysql基础(二)

    多表连接 #多表查询 /* sql99标准 等值连接 ①多表等值连接的结果为多表的交集部分 ② n个连接至少需要 n-1个连接 ③一般需要为表起别名 ④可以搭配前面介绍的所有子句的使用,比如排序,分组 ...

  7. JS实现PC端URL跳转到对应移动端URL

    在做移动端网站时,有时因技术问题或其他原因无法制作响应式版面,而移动端页面只能放到子目录下,但是手机端通过搜索引擎进入网站电脑端子页面,无法匹配到移动端页面,使得用户体验很不好,即影响排名也影响转化. ...

  8. MVVM 小雏形 knockout

    前言 knockout学过的当工具脚本用,就像jquery一样使用,学习成本15分钟,没学过的可学可不学. knockout 是上古神器,话说在远古开天辟地,前端到处是飞禽走兽,一片混乱. 这时候人类 ...

  9. SpringBoot 定制 starter 启动器

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 在实际项目开发中,我们常常会用到各种各样的 starter,这些starter 有的是有 springb ...

  10. Java实现 LeetCode 332 重新安排行程

    332. 重新安排行程 给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序.所有这些机票都属于一个从JFK(肯尼迪国际机场 ...