redis - spring-data-redis简介和入门
2017-05-13 00:00
495 查看
1. 前言
Spring-data-redis是spring的子项目,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅。官网:http://projects.spring.io/spring-data-redis/
项目地址:https://github.com/spring-projects/spring-data-redis
1.1 功能介绍
jedis客户端在编程实施方面存在如下不足:connection管理缺乏自动化,connection-pool的设计缺少必要的容器支持。
数据操作需要关注“序列化”/“反序列化”,因为jedis的客户端API接受的数据类型为string和byte,对结构化数据(json,xml,pojo等)操作需要额外的支持。
务操作纯粹为硬编码。
pub/sub功能,缺乏必要的设计模式支持,对于开发者而言需要关注的太多。
spring-data-redis针对jedis提供了如下功能:
1.连接池自动管理,提供了一个高度封装的“RedisTemplate”类
2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口。
ValueOperations:简单K-V操作
SetOperations:set类型数据操作
ZSetOperations:zset类型数据操作
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作
3.提供了对key的“bound”(绑定)便捷化操作API,可以通过bound封装指定的key,然后进行一系列的操作而无须“显式”的再次指定Key,即BoundKeyOperations,根据数据结构的不同,分为如下:
BoundValueOperations
BoundSetOperations
BoundListOperations
BoundSetOperations
BoundHashOperations
4.将事务操作封装,有容器控制。
5.针对数据的“序列化/反序列化”,提供了多种可选择策略(RedisSerializer)。将在下一小节详细介绍。
6.基于设计模式,和JMS开发思路,将pub/sub的API设计进行了封装,使开发更加便捷。
7.spring-data-redis中,并没有对sharding提供良好的封装,如果你的架构是基于sharding,那么你需要自己去实现,这也是spring-data-redis和jedis相比,唯一缺少的特性。
##1.2 序列化策略
RedisTemplate配置中需要对4个域声明序列化策略,它们使用的策略默认为“JdkSerializationRedisSerializer”,这四种声明域分别是:
keySerializer :对于普通K-V操作时,key采取的序列化策略
valueSerializer:value采取的序列化策略
hashKeySerializer: 在hash数据结构中,hash-key的序列化策略
hashValueSerializer:hash-value的序列化策略
spring-data-redis提供的序列化器有以下几种:
**JdkSerializationRedisSerializer **:POJO对象的存取场景,使用JDK本身序列化机制,将pojo类通过ObjectInputStream/ObjectOutputStream进行序列化操作,最终redis-server中将存储字节序列。是目前最常用的序列化策略。
**StringRedisSerializer **:Key或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封装。是最轻量级和高效的策略。
**JacksonJsonRedisSerializer **:jackson-json工具提供了javabean与json之间的转换能力,可以将pojo实例序列化成json格式存储在redis中,也可以将json格式的数据转换成pojo实例。因为jackson工具在序列化和反序列化时,需要明确指定Class类型,因此此策略封装起来稍微复杂。【需要jackson-mapper-asl工具支持】
**OxmSerializer **:提供了将javabean与xml之间的转换能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存储的数据将是xml工具。不过使用此策略,编程将会有些难度,而且效率最低;不建议使用。【需要spring-oxm模块的支持】
针对“序列化和发序列化”中JdkSerializationRedisSerializer和StringRedisSerializer是最基础的策略,原则上,我们可以将数据存储为任何格式以便应用程序存取和解析(其中应用包括app,hadoop等其他工具),不过在设计时仍然不推荐直接使用“JacksonJsonRedisSerializer”和“OxmSerializer”,因为无论是json还是xml,他们本身仍然是String。如果你的数据需要被第三方工具解析,那么数据应该使用StringRedisSerializer而不是JdkSerializationRedisSerializer。如果你的数据格式必须为json或者xml,那么在编程级别,在redisTemplate配置中仍然使用StringRedisSerializer,在存储之前或者读取之后,使用“SerializationUtils”工具转换转换成json或者xml。
2. 动手吧,少年
首先需要引入依赖<!--redis--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.10.RELEASE</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>4.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.9.RELEASE</version> </dependency>
然后配置redis连接池和连接工厂,再把连接工厂配置到模板中。由于连接工厂的分为单机版和集群版,所以这里分别列出了两个配置
单机版本
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- redis连接池的配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="1"/> <property name="maxTotal" value="5"/> <property name="blockWhenExhausted" value="true"/> <property name="maxWaitMillis" value="30000"/> <property name="testOnBorrow" value="true"/> </bean> <!-- 工厂类配置 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="192.168.88.18"/> <property name="port" value="6379"/> <property name="poolConfig" ref="jedisPoolConfig"/> <property name="timeout" value="15000"/> <property name="usePool" value="true"/> </bean> </beans>
集群版
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Redis集群配置 --> <bean id="redisClusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration"> <property name="maxRedirects" value="3"/> <property name="clusterNodes"> <set> <bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="127.0.0.1"/> <constructor-arg name="port" value="7000"/> </bean> <bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="127.0.0.1"/> <constructor-arg name="port" value="7004"/> </bean> <bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="127.0.0.1"/> <constructor-arg name="port" value="7005"/> </bean> </set> </property> </bean> <!-- redis连接池的配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="1"/> <property name="maxTotal" value="5"/> <property name="blockWhenExhausted" value="true"/> <property name="maxWaitMillis" value="30000"/> <property name="testOnBorrow" value="true"/> </bean> <!-- 工厂类配置 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <constructor-arg name="clusterConfig" ref="redisClusterConfig"/> <property name="poolConfig" ref="jedisPoolConfig"/> <property name="timeout" value="15000"/> <property name="usePool" value="true"/> </bean> </beans>
连接工厂配置到redis模板。除了配置连接工厂的引用,这里还配置了string和hash的key/value序列化的方式,如果redis数据库的数据还打算给其它第三方客户端使用,请采用redis默认的序列化方式,否则当查看redis数据库的时候会大吃一惊(和第三方客户端产生的值不同)。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- redisTemplate配置 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> </bean> </beans>
OK,下面建立测试用例测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring/spring-context.xml") public class AppTest extends AbstractJUnit4SpringContextTests { @Autowired private RedisTemplate redisTemplate; /** * 测试redis的string数据结构 */ @Test public void testRedisString() { //添加一个key ValueOperations<String, String> operations = redisTemplate.opsForValue(); String key = "cache:index"; operations.set(key, "缓存值"); //获取key的值 System.out.println(operations.get(key)); } /** * 测试redis的hash数据结构 */ @Test public void testRedisHash() { HashOperations hashOperations = redisTemplate.opsForHash(); String id = "1000"; //添加一个key String key = "student:" + id; Map<String, String> map = new HashMap<String, String>(); map.put("id", id); map.put("age", String.valueOf(18)); map.put("name", "张三"); hashOperations.putAll(key, map); //获取key的值 System.out.println(hashOperations.entries(key)); } /** * 测试redis的list数据结构 */ @Test public void testRedisList() { ListOperations listOperations = redisTemplate.opsForList(); String queue_key = "queue:message"; redisTemplate.delete(queue_key); listOperations.leftPush(queue_key, "你好"); listOperations.leftPush(queue_key, "再见"); long size = listOperations.size(queue_key); for (int i = 0; i < size; i++) { System.out.println(listOperations.rightPop(queue_key).toString()); } } /** * 测试redis的set数据结构 */ @Test public void testRedisSet() { SetOperations setOperations = redisTemplate.opsForSet(); String key = "like:pager:1000"; setOperations.add(key, "hugo"); setOperations.add(key, "rose"); setOperations.add(key, "jack"); Set members = setOperations.members(key); Iterator iterator = members.iterator(); while (iterator.hasNext()) { String value = (String) iterator.next(); System.out.println(value); } } /** * 测试redis的sorted set数据结构 */ @Test public void testRedisSortedSet() { ZSetOperations zSetOperations = redisTemplate.opsForZSet(); String key = "top:music"; zSetOperations.add(key, "野狼", 88); zSetOperations.add(key, "情人", 175); zSetOperations.add(key, "三国", 15); zSetOperations.add(key, "水浒", 65); } }
3 相关资料与声明
本文涉及代码:http://git.oschina.net/thinwonton/redis-showcase声明,本文的前言部分摘抄于网络。
相关文章推荐
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring-data-redis简介(转)
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- redis实现spring-redis-data的入门实例
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- 快速入门spring-data-redis,轻松上手
- spring-data-redis简介
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
- SpringDataSolr --- 入门简介
- 如何用SpringData连接Redis简单测试
- spring的入门(aop,ioc,bean作用域等)简介
- redis实现 spring-redis-data初学习
- Spring集成Redis实例入门