redis虽然提供了对list set hash等数据类型的支持,但是没有提供对POJO对象的支持,底层都是把对象序列化后再以字符串的方式存储的。因此,Spring data提供了若干个Serializer,主要包括:
- JacksonJsonRedisSerializer
- JdkSerializationRedisSerializer
- OxmSerializer
参见: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对象,如下所示:
- package com.oreilly.springdata.redis;
- import javax.xml.bind.annotation.XmlAccessType;
- import javax.xml.bind.annotation.XmlAccessorType;
- 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”键可以查看到对应的值,内容如下:
"\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查看对应的字符长度:
(integer) 104
上面的代码共进行了100次的存储和获取,其所花时间如下(毫秒):
使用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的内容及内容长度:
"{\"userName\":\"user1\",\"age\":20}"
redis 127.0.0.1:6379> strlen json/user1
(integer) 29
执行花费时间为:
使用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的内容及内容长度:
"<?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
执行花费时间为:
小结
从执行时间上来看,JdkSerializationRedisSerializer是最高效的(毕竟是JDK原生的),但是是序列化的结果字符串是最长的。JSON由于其数据格式的紧凑性,序列化的长度是最小的,时间比前者要多一些。而OxmSerialiabler在时间上看是最长的(当时和使用具体的Marshaller有关)。所以个人的选择是倾向使用JacksonJsonRedisSerializer作为POJO的序列器。