首页 文章资讯内容详情

深入理解Spring Redis的使用 (一)、Spring Redis基本使用

2026-06-01 4 花语

本文内容纲要:

-1.Redis使用场景 -2.配置使用redis -3.RedisTemplate的使用 -4.总结

关于springredis框架的使用,网上的例子很多很多。但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与springredis丰富的api大相径庭,真是浪费了这么优秀的一个框架。这里,我们就对比之前对springorm中对hibernate的使用,来理解使用springredis的使用。(本文章不做redis基本命令使用的讲解)

1.Redis使用场景

Redis是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

我们都知道,在日常的应用中,数据库瓶颈是最容易出现的。数据量太大和频繁的查询,由于磁盘IO性能的局限性,导致项目的性能越来越低。

这时候,基于内存的缓存框架,就能解决我们很多问题。例如Memcache,Redis等。将一些频繁使用的数据放入缓存读取,大大降低了数据库的负担。提升了系统的性能。

其实,对于hibernate的二级缓存,是同样的道理。利用内存高速的读写速度,来解决硬盘的瓶颈。

2.配置使用redis

首先,我们需要引入基本的jar包。maven中的基本引用如下:

<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.4.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.6.2</version> </dependency>

然后,在applicationContext中配置如下:

<beanid="poolConfig"class="redis.clients.jedis.JedisPoolConfig"> <propertyname="maxIdle"value="${redis.maxIdle}"/> <propertyname="maxTotal"value="${redis.maxActive}"/> <propertyname="maxWaitMillis"value="${redis.maxWait}"/> <propertyname="testOnBorrow"value="${redis.testOnBorrow}"/> </bean> <beanid="connectionFactory"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"/> <beanid="stringSerializer"class="org.springframework.data.redis.serializer.StringRedisSerializer"/> <!--开启事务,可以通过transcational注解控制--> <beanid="redisTemplate"class="org.springframework.data.redis.core.RedisTemplate"> <propertyname="connectionFactory"ref="connectionFactory"/> <propertyname="keySerializer"ref="stringSerializer"/> <propertyname="enableTransactionSupport"value="true"/> </bean>

对于hibernate的配置可知,第一个poolconfig是对连接池的配置。包括最大连接数,队列数,存活时间,最大等待时间等等,还有一些额外的配置,请直接点击JedisPoolConfig类源码,进行查看。

这些配置的意思如果不明白的话,一定要去把线程池好好学习下。

第一个配置是连接工厂,顾名思义,最基本的使用一定是对连接的打开和关闭。我们需要为其配置redis服务器的账户密码,端口号。(这里还可以配置数据库的index,但是我使用时候一直使用redis的默认数据库,也就是第0个)

最后一个配置特别重要。这个类似于spring提供的HibernateDaoSupport。

接下来,全部讲解都将围绕这个类展开。

3.RedisTemplate的使用

这个类作为一个模版类,提供了很多快速使用redis的api,而不需要自己来维护连接,事务。

最初的时候,我创建的BaseRedisDao是继承自这个类的。继承的好处是我的每个Dao中,都可以自由的控制序列化器,自由的控制自己是否需要事务,这个先不需要了解,跟着我目前的这种配置方法来即可。

template提供了一系列的operation,比如valueOperation,HashOperation,ListOperation,SetOperation等,用来操作不同数据类型的Redis。

并且,RedisTemplate还提供了对应的*OperationsEditor,用来通过RedisTemplate直接注入对应的Operation。我们暂时不讲这个。

对于下面的test1方法,我们暂时不用考虑,先了解通过RedisTemplate来使用connection操作Redis。

Test代码如下:

packagecn.test.spjedis; importjavax.annotation.Resource; importorg.junit.Test; importorg.junit.runner.RunWith; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.dao.DataAccessException; importorg.springframework.data.redis.connection.RedisConnection; importorg.springframework.data.redis.core.RedisCallback; importorg.springframework.data.redis.core.RedisTemplate; importorg.springframework.data.redis.core.ValueOperations; importorg.springframework.test.context.ContextConfiguration; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; importcom.cn.redis2.dao.IncrDao; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext.xml") publicclassTestRedis{ @Resource(name="redisTemplate") privateRedisTemplate<String,String>template;//injectthetemplateasListOperations //至于这个为什么可以注入。需要参考AbstractBeanFactorydoGetBean //super.setValue(((RedisOperations)value).opsForValue());就这一行代码依靠一个editor @Resource(name="redisTemplate") privateValueOperations<String,Object>vOps; publicvoidtestSet(){ template.execute(newRedisCallback<Boolean>(){ @Override publicBooleandoInRedis(RedisConnectionconnection)throwsDataAccessException{ byte[]key="tempkey".getBytes(); byte[]value="tempvalue".getBytes(); connection.set(key,value); returntrue; } }); } publicvoidtestSet1(){ vOps.set("tempkey","tempvalue"); } @Autowired privateIncrDaoincr; @Test publicvoidaddLink(){ System.out.println(incr.incr(13)); System.out.println(incr.get(13)); } }

这个是对String类型插入的两个测试。test方法中,使用了模版类提交回调(RedisCallBack)的方法来使用jedisconnection操作数据。这一部分,有没有似曾相识呢?

HibernateTemplate的HibernateCallback,以及HibernateSession类中的doWork以及doReturningWork方法,都是使用了这样的机制,方便对于连接或者session的统一管理。

publicintexcuteHqlUpdate(finalStringhql,finalObject...params){ returngetHibernateTemplate().executeWithNativeSession(newHibernateCallback<Integer>(){ @Override @SuppressWarnings("unchecked") publicIntegerdoInHibernate(Sessionsession)throwsHibernateException{ QueryqueryObject=session.createQuery(hql); if(params!=null){ for(inti=0;i<params.length;i++){ queryObject.setParameter(i,params[i]); } } returnqueryObject.executeUpdate(); } }); }

4.总结

我们这节,讲了springredis的配置使用,基本特性,以及引入使用RedisTemplate。通过之前HibernateTemplate的对比,也应该对RedisTemplate的基本设计有了一定的了解。下节,我们将进行深入学习RedisTempalte。

本文内容总结:1.Redis使用场景,2.配置使用redis,3.RedisTemplate的使用,4.总结,

原文链接:https://www.cnblogs.com/luochengqiuse/p/4638988.html