問題
最近在整一個spring data redis,網上有一本《Spring Data》的電子書(我一個朋友正在翻譯,應該今年會有中文版出來,人郵的),下載來看了一下,其中第8章講到了Spring data對redis的支持。
redis雖然提供了對list set hash等數據類型的支持,可是沒有提供對POJO對象的支持,底層都是把對象序列化後再以字符串的方式存儲的。所以,Spring data提供了若干個Serializer,主要包括:
java
JacksonJsonRedisSerializergit
JdkSerializationRedisSerializergithub
OxmSerializerredis
參見:http://static.springsource.org/spring-data/data-keyvalue/docs/1.0.x/api/
這裏,我第一是想測試一下三者的使用,第二是想看看它們的使用效果。
準備工做
下載源碼
我直接在《Spring Data》書的源碼基礎上改,從這下載書的源碼:https://github.com/SpringSource/spring-data-book
打開redis子項目,因爲是以Maven組織的,因此不用關心包的問題。
添加一個測試的Entity
因爲咱們但願測試使用Redis保存POJO對象,所以咱們在com.oreilly.springdata.redis包下建立一個User對象,以下所示:
spring
package com.oreilly.springdata.redis; api
import javax.xml.bind.annotation.XmlAccessType; 服務器
import javax.xml.bind.annotation.XmlAccessorType; ide
import javax.xml.bind.annotation.XmlAttribute; 測試
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
/**
* @author : stamen
* @date: 13-7-16
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "user")
public class User implements Serializable {
@XmlAttribute
private String userName;
@XmlAttribute
private int age;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
因爲後面,咱們須要使用OXM及Jackson將進行對象序列,爲了控制對象的序列化,所以打上了JSR 175註解。
更改ApplicationConfig
ApplicationConfig是Spring容器的配置類,要根據你的環境進行更改,個人更改成:
package com.oreilly.springdata.redis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.OxmSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Jon Brisbin
*/
@Configuration
public abstract class ApplicationConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory cf = new JedisConnectionFactory();
cf.setHostName("10.188.182.140");
cf.setPort(6379);
cf.setPassword("superman");
cf.afterPropertiesSet();
return cf;
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate rt = new RedisTemplate();
rt.setConnectionFactory(redisConnectionFactory());
return rt;
}
private static Map<Class, JAXBContext> jaxbContextHashMap = new ConcurrentHashMap<Class, JAXBContext>();
@Bean
public OxmSerializer oxmSerializer() throws Throwable{
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
Map<String,Object> properties = new HashMap<String, Object>();//建立映射,用於設置Marshaller屬性
properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //放置xml自動縮進屬性
properties.put(Marshaller.JAXB_ENCODING,"utf-8"); //放置xml自動縮進屬性
jaxb2Marshaller.setClassesToBeBound(User.class);//映射的xml類放入JAXB環境中
jaxb2Marshaller.setMarshallerProperties(properties);//設置Marshaller屬性
return new OxmSerializer(jaxb2Marshaller,jaxb2Marshaller);
}
public static enum StringSerializer implements RedisSerializer<String> {
INSTANCE;
@Override
public byte[] serialize(String s) throws SerializationException {
return (null != s ? s.getBytes() : new byte[0]);
}
@Override
public String deserialize(byte[] bytes) throws SerializationException {
if (bytes.length > 0) {
return new String(bytes);
} else {
return null;
}
}
}
public static enum LongSerializer implements RedisSerializer<Long> {
INSTANCE;
@Override
public byte[] serialize(Long aLong) throws SerializationException {
if (null != aLong) {
return aLong.toString().getBytes();
} else {
return new byte[0];
}
}
@Override
public Long deserialize(byte[] bytes) throws SerializationException {
if (bytes.length > 0) {
return Long.parseLong(new String(bytes));
} else {
return null;
}
}
}
public static enum IntSerializer implements RedisSerializer<Integer> {
INSTANCE;
@Override
public byte[] serialize(Integer i) throws SerializationException {
if (null != i) {
return i.toString().getBytes();
} else {
return new byte[0];
}
}
@Override
public Integer deserialize(byte[] bytes) throws SerializationException {
if (bytes.length > 0) {
return Integer.parseInt(new String(bytes));
} else {
return null;
}
}
}
}
1)redisConnectionFactory()配置瞭如何鏈接Redsi服務器(如何安裝Redis,參見:http://redis.io/download)
2)oxmSerializer()是我新增的,用於定義一個基於Jaxb2Marshaller的OxmSerializer Bean(後面將會用到)
編寫測試用例
打開KeyValueSerializersTest,咱們幾個額外的測試用例都將寫在該測試類中:
使用JdkSerializationRedisSerializer序列化
@Test
public void testJdkSerialiable() {
RedisTemplate<String, Serializable> redis = new RedisTemplate<String, Serializable>();
redis.setConnectionFactory(connectionFactory);
redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
redis.setValueSerializer(new JdkSerializationRedisSerializer());
redis.afterPropertiesSet();
ValueOperations<String, Serializable> ops = redis.opsForValue();
User user1 = new User();
user1.setUserName("user1");
user1.setAge(20);
String key1 = "users/user1";
User user11 = null;
long begin = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
ops.set(key1,user1);
user11 = (User)ops.get(key1);
}
long time = System.currentTimeMillis() - begin;
System.out.println("jdk time:"+time);
assertThat(user11.getUserName(),is("user1"));
}
JdkSerializationRedisSerializer支持對全部實現了Serializable的類進行序列化。運行該測試用例,咱們經過redis-cli 經過「users/user1」鍵能夠查看到對應的值,內容以下:
引用
redis 127.0.0.1:6379> get users/user1
"\xac\xed\x00\x05sr\x00!com.oreilly.springdata.redis.User\xb1\x1c \n\xcd\xed%\xd8\x02\x00\x02I\x00\x03ageL\x00\buserNamet\x00\x12Ljava/lang/String;xp\x00\x00\x00\x14t\x00\x05user1"
經過strlen查看對應的字符長度:
引用
redis 127.0.0.1:6379> strlen users/user1
(integer) 104
上面的代碼共進行了100次的存儲和獲取,其所花時間以下(毫秒):
引用
jdk time:266
使用JacksonJsonRedisSerializer序列化
@Test
public void testJacksonSerialiable() {
RedisTemplate<String, Object> redis = new RedisTemplate<String, Object>();
redis.setConnectionFactory(connectionFactory);
redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
redis.setValueSerializer(new JacksonJsonRedisSerializer<User>(User.class));
redis.afterPropertiesSet();
ValueOperations<String, Object> ops = redis.opsForValue();
User user1 = new User();
user1.setUserName("user1");
user1.setAge(20);
User user11 = null;
String key1 = "json/user1";
long begin = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
ops.set(key1,user1);
user11 = (User)ops.get(key1);
}
long time = System.currentTimeMillis() - begin;
System.out.println("json time:"+time);
assertThat(user11.getUserName(),is("user1"));
}
運行後,查看redis的內容及內容長度:
引用
redis 127.0.0.1:6379> get json/user1
"{\"userName\":\"user1\",\"age\":20}"
redis 127.0.0.1:6379> strlen json/user1
(integer) 29
執行花費時間爲:
引用
json time:224
使用OxmSerialiable序列化
@Test
public void testOxmSerialiable() throws Throwable{
RedisTemplate<String, Object> redis = new RedisTemplate<String, Object>();
redis.setConnectionFactory(connectionFactory);
redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
redis.setValueSerializer(oxmSerializer);
redis.afterPropertiesSet();
ValueOperations<String, Object> ops = redis.opsForValue();
User user1 = new User();
user1.setUserName("user1");
user1.setAge(20);
User user11 = null;
String key1 = "oxm/user1";
long begin = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
ops.set(key1,user1);
user11 = (User)ops.get(key1);
}
long time = System.currentTimeMillis() - begin;
System.out.println("oxm time:"+time);
assertThat(user11.getUserName(),is("user1"));
}
運行後,查看redis的內容及內容長度:
引用
redis 127.0.0.1:6379> get oxm/user1
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<user age=\"20\" userName=\"user1\"/>\n"
redis 127.0.0.1:6379> strlen oxm/user1
(integer) 90
執行花費時間爲:
引用
oxm time:335
小結
從執行時間上來看,JdkSerializationRedisSerializer是最高效的(畢竟是JDK原生的),可是是序列化的結果字符串是最長的。JSON因爲其數據格式的緊湊性,序列化的長度是最小的,時間比前者要多一些。而OxmSerialiabler在時間上看是最長的(當時和使用具體的Marshaller有關)。因此我的的選擇是傾向使用JacksonJsonRedisSerializer做爲POJO的序列器。
redis.zip (11.1 KB)