1、简介
Spring-data-redis是spring大家族的一部分,提供了在spring应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。
2、功能
spring-data-redis针对jedis提供了如下功能:
1>连接池自动管理,提供了一个高度封装的“RedisTemplate”类
2>针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
ValueOperations:简单K-V操作
SetOperations:set类型数据操作
ZSetOperations:zset类型数据操作
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作
3、小demo练习
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)创建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)创建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> |
2> hash类型的操作
创建测试类TestHash.java
(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); }
|
(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"); } |