SpringDataRedis简介、入门demo,缓存广告的增删改查以及清除缓存

SpringDataRedis简介

5.1 Spring Data Redis

Spring-data-redis是spring大家族的一部分,提供了在spring应用中通过简单的配置访问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类型的数据操作

5.2 Spring Data Redis入门小Demo

5.2.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>

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

redis.host=127.0.0.1 

redis.port=6379 

redis.pass=

redis.database=0 

redis.maxIdle=300 

redis.maxWait=3000 

redis.testOnBorrow=true 

(5)在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实例均是可用的;

5.2.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("cblue");

}

@Test

public void getValue(){

String str = (String) redisTemplate.boundValueOps("name").get();

System.out.println(str);

}

@Test

public void deleteValue(){

redisTemplate.delete("name");;

}

}

5.2.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");

}

}

 

5.2.4 List类型操作

创建测试类TestList

(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);

}

运行结果:

[张飞, 关羽, 刘备]

  1. 根据索引查询元素

/**

 * 查询集合某个元素

 */

@Test

public void testSearchByIndex(){

String s = (String) redisTemplate.boundListOps("namelist1").index(1);

System.out.println(s);

}

  1. 移除某个元素的值

/**

 * 移除集合某个元素

 */

@Test

public void testRemoveByIndex(){

redisTemplate.boundListOps("namelist1").remove(1, "关羽");

}

5.2.5 Hash类型操作

创建测试类TestHash

(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

/**

 * 提取所有的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提取值

/**

 * 根据key提取所有值

 */

@Test

public void testGetValueByKey(){

Object object = redisTemplate.boundHashOps("namehash").get("b");

System.out.println(object);

}

运行结果:

悟空

(5)根据KEY移除值

/**

 * 根据key移除值

 */

@Test

public void testRemoveValueByKey(){

redisTemplate.boundHashOps("namehash").delete("c");

}

运行后再次查看集合内容:

[唐僧, 悟空, 沙僧]

6.网站首页-缓存广告数据

6.1需求分析

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

6.2读取缓存

6.2.1公共组件层

因为缓存对于我们整个的系统来说是通用功能。广告需要用,其它数据可能也会用到,所以我们将配置放在公共组件层(mall-common)中较为合理。

(1)mall-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 拷贝至mall-common

(3)mall-content-service依赖mall-common

6.2.2后端服务实现层

修改 mall-content-service的ContentServiceImpl

@Autowired

private RedisTemplate redisTemplate;

@Override

public List<TbContent> findByCategoryId(Long categoryId) {

List<TbContent> contentList= (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);

if(contentList==null){

System.out.println("从数据库读取数据放入缓存");

//根据广告分类ID查询广告列表

TbContentExample contentExample=new TbContentExample();

Criteria criteria2 = contentExample.createCriteria();

criteria2.andCategoryIdEqualTo(categoryId);

criteria2.andStatusEqualTo("1");//开启状态

contentExample.setOrderByClause("sort_order");//排序

contentList = contentMapper.selectByExample(contentExample);//获取广告列表

redisTemplate.boundHashOps("content").put(categoryId, contentList);//存入缓存

}else{

System.out.println("从缓存读取数据");

}

return  contentList;

}

 

6.3更新缓存

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

6.3.1新增广告后清除缓存

修改mall-content-service工程ContentServiceImpl.java 的add方法

/**

 * 增加

 */

@Override

public void add(TbContent content) {

contentMapper.insert(content);

//清除缓存

redisTemplate.boundHashOps("content").delete(content.getCategoryId());

}

6.3.2修改广告后清除缓存

考虑到用户可能会修改广告的分类,这样需要把原分类的缓存和新分类的缓存都清除掉。

/**

 * 修改

 */

@Override

public void update(TbContent content){

//查询修改前的分类Id

Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();

redisTemplate.boundHashOps("content").delete(categoryId);

contentMapper.updateByPrimaryKey(content);

//如果分类ID发生了修改,清除修改后的分类ID的缓存

if(categoryId.longValue()!=content.getCategoryId().longValue()){

redisTemplate.boundHashOps("content").delete(content.getCategoryId());

}

}

6.3.3删除广告后清除缓存

/**

 * 批量删除

 */

@Override

public void delete(Long[] ids) {

for(Long id:ids){

//清除缓存

Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();//广告分类ID

redisTemplate.boundHashOps("content").delete(categoryId);

contentMapper.deleteByPrimaryKey(id);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值