Spring-data-redis是spring大家族的一部分,提供了在srping應(yīng)用中通過簡單的配置訪問redis服務(wù),對reids底層開發(fā)包(Jedis, JRedis, and RJC)進行了高度封裝,RedisTemplate提供了redis各種操作、異常處理及序列化,支持發(fā)布訂閱,并對spring 3.1 cache進行了實現(xiàn)。
官網(wǎng):http://projects.spring.io/spring-data-redis/
項目地址:https://github.com/spring-projects/spring-data-redis
一、spring-data-redis功能介紹
jedis客戶端在編程實施方面存在如下不足:
1)connection管理缺乏自動化,connection-pool的設(shè)計缺少必要的容器支持。
2)數(shù)據(jù)操作需要關(guān)注“序列化”/“反序列化”,因為jedis的客戶端API接受的數(shù)據(jù)類型為string和byte,對結(jié)構(gòu)化數(shù)據(jù)(json,xml,pojo等)操作需要額外的支持。
3)事務(wù)操作純粹為硬編碼。
4)pub/sub功能,缺乏必要的設(shè)計模式支持,對于開發(fā)者而言需要關(guān)注的太多。
spring-data-redis針對jedis提供了如下功能:
1.連接池自動管理,提供了一個高度封裝的“RedisTemplate”類
2.針對jedis客戶端中大量api進行了歸類封裝,將同一類型操作封裝為operation接口
- ValueOperations:簡單K-V操作
- SetOperations:set類型數(shù)據(jù)操作
- ZSetOperations:zset類型數(shù)據(jù)操作
- HashOperations:針對map類型的數(shù)據(jù)操作
- ListOperations:針對list類型的數(shù)據(jù)操作
3.提供了對key的“bound”(綁定)便捷化操作API,可以通過bound封裝指定的key,然后進行一系列的操作而無須“顯式”的再次指定Key,即BoundKeyOperations:
- BoundValueOperations
- BoundSetOperations
- BoundListOperations
- BoundSetOperations
- BoundHashOperations
4.將事務(wù)操作封裝,有容器控制。
5.針對數(shù)據(jù)的“序列化/反序列化”,提供了多種可選擇策略(RedisSerializer)
JdkSerializationRedisSerializer:POJO對象的存取場景,使用JDK本身序列化機制,將pojo類通過ObjectInputStream/ObjectOutputStream進行序列化操作,最終redis-server中將存儲字節(jié)序列。是目前最常用的序列化策略。
StringRedisSerializer:Key或者value為字符串的場景,根據(jù)指定的charset對數(shù)據(jù)的字節(jié)序列編碼成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封裝。是最輕量級和高效的策略。
JacksonJsonRedisSerializer:jackson-json工具提供了javabean與json之間的轉(zhuǎn)換能力,可以將pojo實例序列化成json格式存儲在redis中,也可以將json格式的數(shù)據(jù)轉(zhuǎn)換成pojo實例。因為jackson工具在序列化和反序列化時,需要明確指定Class類型,因此此策略封裝起來稍微復(fù)雜。【需要jackson-mapper-asl工具支持】
OxmSerializer:提供了將javabean與xml之間的轉(zhuǎn)換能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存儲的數(shù)據(jù)將是xml工具。不過使用此策略,編程將會有些難度,而且效率最低;不建議使用。【需要spring-oxm模塊的支持】
針對“序列化和發(fā)序列化”中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎(chǔ)的策略,原則上,我們可以將數(shù)據(jù)存儲為任何格式以便應(yīng)用程序存取和解析(其中應(yīng)用包括app,hadoop等其他工具),不過在設(shè)計時仍然不推薦直接使用“JacksonJsonRedisSerializer”和“OxmSerializer”,因為無論是json還是xml,他們本身仍然是String。如果你的數(shù)據(jù)需要被第三方工具解析,那么數(shù)據(jù)應(yīng)該使用StringRedisSerializer而不是JdkSerializationRedisSerializer。如果你的數(shù)據(jù)格式必須為json或者xml,那么在編程級別,在redisTemplate配置中仍然使用StringRedisSerializer,在存儲之前或者讀取之后,使用“SerializationUtils”工具轉(zhuǎn)換轉(zhuǎn)換成json或者xml,請參見下文實例。
6.基于設(shè)計模式,和JMS開發(fā)思路,將pub/sub的API設(shè)計進行了封裝,使開發(fā)更加便捷。
7.spring-data-redis中,并沒有對sharding提供良好的封裝,如果你的架構(gòu)是基于sharding,那么你需要自己去實現(xiàn),這也是sdr和jedis相比,唯一缺少的特性。
二、serializer策略
spring-data-redis提供了多種serializer策略,這對使用jedis的開發(fā)者而言,實在是非常便捷。sdr提供了4種內(nèi)置的serializer:
JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),數(shù)據(jù)以字節(jié)流存儲
StringRedisSerializer:字符串編碼,數(shù)據(jù)以string存儲
JacksonJsonRedisSerializer:json格式存儲
OxmSerializer:xml格式存儲
其中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎(chǔ)的序列化策略,其中“JacksonJsonRedisSerializer”與“OxmSerializer”都是基于stirng存儲,因此它們是較為“高級”的序列化(最終還是使用string解析以及構(gòu)建java對象)。
RedisTemplate中需要聲明4種serializer,默認(rèn)為“JdkSerializationRedisSerializer”:
1) keySerializer :對于普通K-V操作時,key采取的序列化策略
2) valueSerializer:value采取的序列化策略
3) hashKeySerializer: 在hash數(shù)據(jù)結(jié)構(gòu)中,hash-key的序列化策略
4) hashValueSerializer:hash-value的序列化策略
無論如何,建議key/hashKey采用StringRedisSerializer。
三、使用實例
1.添加jar依賴
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< dependency > < groupId >redis.clients</ groupId > < artifactId >jedis</ artifactId > < version >2.3.1</ version > </ dependency > < dependency > < groupId >org.springframework.data</ groupId > < artifactId >spring-data-redis</ artifactId > < version >1.5.0.RELEASE</ version > </ dependency > < dependency > < groupId >org.slf4j</ groupId > < artifactId >slf4j-log4j12</ artifactId > < version >1.7.10</ version > </ dependency > |
2.spring配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
<? 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" xmlns:p = "http://www.springframework.org/schema/p" 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"> < context:component-scan base-package = "cn.slimsmart.redis.spring" annotation-config = "true" /> < bean id = "jedisPoolConfig" class = "redis.clients.jedis.JedisPoolConfig" > < property name = "maxTotal" value = "10" ></ property > < property name = "maxIdle" value = "10" ></ property > < property name = "minIdle" value = "2" ></ property > < property name = "maxWaitMillis" value = "15000" ></ property > < property name = "minEvictableIdleTimeMillis" value = "300000" ></ property > < property name = "numTestsPerEvictionRun" value = "3" ></ property > < property name = "timeBetweenEvictionRunsMillis" value = "60000" ></ property > < property name = "testOnBorrow" value = "true" ></ property > < property name = "testOnReturn" value = "true" ></ property > < property name = "testWhileIdle" value = "true" ></ property > </ bean > < bean id = "jedisConnectionFactory" class = "org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method = "destroy" > < property name = "hostName" value = "192.168.100.205" /> < property name = "port" value = "6379" /> < property name = "timeout" value = "15000" /> < property name = "database" value = "0" /> < property name = "password" value = "" /> < property name = "usePool" value = "true" /> < property name = "poolConfig" ref = "jedisPoolConfig" /> </ bean > <!-- redis template definition p表示對該bean里面的屬性進行注入,格式為p:屬性名=注入的對象 效果與在bean里面使用<property>標(biāo)簽一樣 --> < bean id = "redisTemplate" class = "org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref = "jedisConnectionFactory" > <!-- 序列化方式 建議key/hashKey采用StringRedisSerializer。 --> < property name = "keySerializer" > < bean class = "org.springframework.data.redis.serializer.StringRedisSerializer" /> </ property > < property name = "hashKeySerializer" > < bean class = "org.springframework.data.redis.serializer.StringRedisSerializer" /> </ property > < property name = "valueSerializer" > < bean class = "org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </ property > < property name = "hashValueSerializer" > < bean class = "org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </ property > </ bean > <!-- 對string操作的封裝 --> < bean id = "stringRedisTemplate" class = "org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref = "jedisConnectionFactory" /> <!-- <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate"/> --> </ beans > |
3.java代碼
實體類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package cn.slimsmart.redis.spring.data.redis.demo; import java.io.Serializable; import java.util.Date; public class Order implements Serializable{ private static final long serialVersionUID = 1L; private String id; private String orderNo; private double price; private Date createDate; public Order(String id,String orderNo, double price,Date createDate){ this .id = id; this .orderNo = orderNo; this .price = price; this .createDate = createDate; } public Order(){ } public String getId() { return id; } public void setId(String id) { this .id = id; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this .orderNo = orderNo; } public double getPrice() { return price; } public void setPrice( double price) { this .price = price; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this .createDate = createDate; } } |
redis操作類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package cn.slimsmart.redis.spring.data.redis.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Repository; @Repository public class OrderDao { @Autowired private RedisTemplate<String,Order> redisTemplate; public void save(Order order) { /*redisTemplate.opsForList(); redisTemplate.opsForSet(); redisTemplate.opsForHash()*/ ValueOperations<String, Order> valueOper = redisTemplate.opsForValue(); valueOper.set(order.getId(), order); } public Order read(String id) { ValueOperations<String, Order> valueOper = redisTemplate.opsForValue(); return valueOper.get(id); } public void delete(String id) { ValueOperations<String, Order> valueOper = redisTemplate.opsForValue(); RedisOperations<String,Order> RedisOperations = valueOper.getOperations(); RedisOperations.delete(id); } } |
參考代碼:spring-data-redis-demo.rar
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/zhu_tianwei/article/details/44923001