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对象,如下所示:

  1. package com.oreilly.springdata.redis;
  2. import javax.xml.bind.annotation.XmlAccessType;
  3. import javax.xml.bind.annotation.XmlAccessorType;
  4. import javax.xml.bind.annotation.XmlAttribute;
  5. import javax.xml.bind.annotation.XmlRootElement;
  6. import java.io.Serializable;
  7. /**
  8. * @author : stamen
  9. * @date: 13-7-16
  10. */
  11. @XmlAccessorType(XmlAccessType.FIELD)
  12. @XmlRootElement(name = "user")
  13. public class User implements Serializable {
  14. @XmlAttribute
  15. private String userName;
  16. @XmlAttribute
  17. private int age;
  18. public String getUserName() {
  19. return userName;
  20. }
  21. public void setUserName(String userName) {
  22. this.userName = userName;
  23. }
  24. public int getAge() {
  25. return age;
  26. }
  27. public void setAge(int age) {
  28. this.age = age;
  29. }
  30. }

由于后面,我们需要使用OXM及Jackson将进行对象序列,为了控制对象的序列化,因此打上了JSR 175注解。

更改ApplicationConfig

ApplicationConfig是Spring容器的配置类,要根据你的环境进行更改,我的更改为:

  1. package com.oreilly.springdata.redis;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.data.redis.serializer.OxmSerializer;
  8. import org.springframework.data.redis.serializer.RedisSerializer;
  9. import org.springframework.data.redis.serializer.SerializationException;
  10. import org.springframework.oxm.jaxb.Jaxb2Marshaller;
  11. import javax.xml.bind.JAXBContext;
  12. import javax.xml.bind.Marshaller;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.concurrent.ConcurrentHashMap;
  16. /**
  17. * @author Jon Brisbin
  18. */
  19. @Configuration
  20. public abstract class ApplicationConfig {
  21. @Bean
  22. public RedisConnectionFactory redisConnectionFactory() {
  23. JedisConnectionFactory cf = new JedisConnectionFactory();
  24. cf.setHostName("10.188.182.140");
  25. cf.setPort(6379);
  26. cf.setPassword("superman");
  27. cf.afterPropertiesSet();
  28. return cf;
  29. }
  30. @Bean
  31. public RedisTemplate redisTemplate() {
  32. RedisTemplate rt = new RedisTemplate();
  33. rt.setConnectionFactory(redisConnectionFactory());
  34. return rt;
  35. }
  36. private static Map<Class, JAXBContext> jaxbContextHashMap = new ConcurrentHashMap<Class, JAXBContext>();
  37. @Bean
  38. public OxmSerializer oxmSerializer() throws Throwable{
  39. Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
  40. Map<String,Object> properties = new HashMap<String, Object>();//创建映射,用于设置Marshaller属性
  41. properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);   //放置xml自动缩进属性
  42. properties.put(Marshaller.JAXB_ENCODING,"utf-8");   //放置xml自动缩进属性
  43. jaxb2Marshaller.setClassesToBeBound(User.class);//映射的xml类放入JAXB环境中
  44. jaxb2Marshaller.setMarshallerProperties(properties);//设置Marshaller属性
  45. return  new OxmSerializer(jaxb2Marshaller,jaxb2Marshaller);
  46. }
  47. public static enum StringSerializer implements RedisSerializer<String> {
  48. INSTANCE;
  49. @Override
  50. public byte[] serialize(String s) throws SerializationException {
  51. return (null != s ? s.getBytes() : new byte[0]);
  52. }
  53. @Override
  54. public String deserialize(byte[] bytes) throws SerializationException {
  55. if (bytes.length > 0) {
  56. return new String(bytes);
  57. } else {
  58. return null;
  59. }
  60. }
  61. }
  62. public static enum LongSerializer implements RedisSerializer<Long> {
  63. INSTANCE;
  64. @Override
  65. public byte[] serialize(Long aLong) throws SerializationException {
  66. if (null != aLong) {
  67. return aLong.toString().getBytes();
  68. } else {
  69. return new byte[0];
  70. }
  71. }
  72. @Override
  73. public Long deserialize(byte[] bytes) throws SerializationException {
  74. if (bytes.length > 0) {
  75. return Long.parseLong(new String(bytes));
  76. } else {
  77. return null;
  78. }
  79. }
  80. }
  81. public static enum IntSerializer implements RedisSerializer<Integer> {
  82. INSTANCE;
  83. @Override
  84. public byte[] serialize(Integer i) throws SerializationException {
  85. if (null != i) {
  86. return i.toString().getBytes();
  87. } else {
  88. return new byte[0];
  89. }
  90. }
  91. @Override
  92. public Integer deserialize(byte[] bytes) throws SerializationException {
  93. if (bytes.length > 0) {
  94. return Integer.parseInt(new String(bytes));
  95. } else {
  96. return null;
  97. }
  98. }
  99. }
  100. }

1)redisConnectionFactory()配置了如何连接Redsi服务器(如何安装Redis,参见:http://redis.io/download) 
   2)oxmSerializer()是我新增的,用于定义一个基于Jaxb2Marshaller的OxmSerializer Bean(后面将会用到)

编写测试用例

打开KeyValueSerializersTest,我们几个额外的测试用例都将写在该测试类中:

使用JdkSerializationRedisSerializer序列化

  1. @Test
  2. public void testJdkSerialiable() {
  3. RedisTemplate<String, Serializable> redis = new RedisTemplate<String, Serializable>();
  4. redis.setConnectionFactory(connectionFactory);
  5. redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
  6. redis.setValueSerializer(new JdkSerializationRedisSerializer());
  7. redis.afterPropertiesSet();
  8. ValueOperations<String, Serializable> ops = redis.opsForValue();
  9. User user1 = new User();
  10. user1.setUserName("user1");
  11. user1.setAge(20);
  12. String key1 = "users/user1";
  13. User user11 = null;
  14. long begin = System.currentTimeMillis();
  15. for (int i = 0; i < 100; i++) {
  16. ops.set(key1,user1);
  17. user11 = (User)ops.get(key1);
  18. }
  19. long time = System.currentTimeMillis() - begin;
  20. System.out.println("jdk time:"+time);
  21. assertThat(user11.getUserName(),is("user1"));
  22. }

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序列化

  1. @Test
  2. public void testJacksonSerialiable() {
  3. RedisTemplate<String, Object> redis = new RedisTemplate<String, Object>();
  4. redis.setConnectionFactory(connectionFactory);
  5. redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
  6. redis.setValueSerializer(new JacksonJsonRedisSerializer<User>(User.class));
  7. redis.afterPropertiesSet();
  8. ValueOperations<String, Object> ops = redis.opsForValue();
  9. User user1 = new User();
  10. user1.setUserName("user1");
  11. user1.setAge(20);
  12. User user11 = null;
  13. String key1 = "json/user1";
  14. long begin = System.currentTimeMillis();
  15. for (int i = 0; i < 100; i++) {
  16. ops.set(key1,user1);
  17. user11 = (User)ops.get(key1);
  18. }
  19. long time = System.currentTimeMillis() - begin;
  20. System.out.println("json time:"+time);
  21. assertThat(user11.getUserName(),is("user1"));
  22. }

运行后,查看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序列化

  1. @Test
  2. public void testOxmSerialiable() throws Throwable{
  3. RedisTemplate<String, Object> redis = new RedisTemplate<String, Object>();
  4. redis.setConnectionFactory(connectionFactory);
  5. redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);
  6. redis.setValueSerializer(oxmSerializer);
  7. redis.afterPropertiesSet();
  8. ValueOperations<String, Object> ops = redis.opsForValue();
  9. User user1 = new User();
  10. user1.setUserName("user1");
  11. user1.setAge(20);
  12. User user11 = null;
  13. String key1 = "oxm/user1";
  14. long begin = System.currentTimeMillis();
  15. for (int i = 0; i < 100; i++) {
  16. ops.set(key1,user1);
  17. user11 = (User)ops.get(key1);
  18. }
  19. long time = System.currentTimeMillis() - begin;
  20. System.out.println("oxm time:"+time);
  21. assertThat(user11.getUserName(),is("user1"));
  22. }

运行后,查看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的序列器。

关于Spring Data redis几种对象序列化的比较的更多相关文章

  1. Spring Data Redis入门示例:数据序列化 (四)

    概述 RedisTemplate默认使用的是基于JDK的序列化器,所以存储在Redis的数据如果不经过相应的反序列化,看到的结果是这个样子的: 可以看到,出现了乱码,在程序层面上,不会影响程序的运行, ...

  2. 关于spring data redis repository @RedisHash注解的对象上有DateTime属性字段的问题

    当你save保存的时候你会发现出现StackOverflow Exception,很明显出现了无限循环,可是仅仅是一个save操作,哪里来的无限循环呢? 最终发现就是DateTime导致的,因为将对象 ...

  3. spring mvc Spring Data Redis RedisTemplate [转]

    http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...

  4. Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解

    一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...

  5. spring data redis 理解

    前言 Spring Data Redis project,应用了Spring概念来开发使用键值形式的数据存储的解决方案.我们(官方)提供了一个 "template" ,这是一个高级 ...

  6. Spring Data Redis 详解及实战一文搞定

    SDR - Spring Data Redis的简称. Spring Data Redis提供了从Spring应用程序轻松配置和访问Redis的功能.它提供了与商店互动的低级别和高级别抽象,使用户免受 ...

  7. 关于在项目中使用spring data redis与jedis的选择

    项目中需要用到redis,主要用来作为缓存,redis的客户端有两种实现方式,一是可以直接调用jedis来实现,二是可以使用spring data redis,通过spring的封装来调用. 应该使用 ...

  8. Spring Data Redis学习

    本文是从为知笔记上复制过来的,懒得调整格式了,为知笔记版本是带格式的,内容也比这里全.点这里 为知笔记版本 Spring Data Redis 学习 Version 1.8.4.Release 前言 ...

  9. Redis(八):spring data redis 理解

    前言 Spring Data Redis project,应用了Spring概念来开发使用键值形式的数据存储的解决方案.我们(官方)提供了一个 "template" ,这是一个高级 ...

随机推荐

  1. python实现判断一个字符串是否是合法IP地址

    #!usr/bin/env python #encoding:utf-8 ''''' __Author__:沂水寒城 功能:判断一个字符串是否是合法IP地址 ''' import re def jud ...

  2. DNS中NS和SOA区别

    ns 授權很簡單… 假設你註冊的 domain 叫 abc.com ,而你有 ns1 與 ns2 兩台 server . 那,你必需從 .com 的權威伺服器授權給你,其設定或類似如此: $ORIGI ...

  3. 试玩mpvue,用vue的开发模式开发微信小程序

    mpvue,美团开源的vue文件转换成小程序的文件格式,今天玩了一下练练手 mpvue文档地址: http://mpvue.com/mpvue/#_1 暂时有几个点需要注意的: 1.新增页面需要重新启 ...

  4. 【pc杂谈】win7系统通过虚拟网卡共享wifi

    用管理员权限进入dos命令行 启用并设定虚拟WiFi网卡:netsh wlan set hostednetwork mode=allow  ssid=paulnet key=paulwinflo(注意 ...

  5. eclipse+maven springMVC搭建

    1.新建项目: 选择Maven Project 选择项目位置,这里我选择的是C:\Users\admin\workspace\practice 选择maven项目类型,这里选择webapp: 填写Gr ...

  6. 搜索引擎Lucene之皮毛

    一.Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索 ...

  7. python + docker, 实现天气数据 从FTP获取以及持久化(一)

    前情提要 最近项目需要天气数据(预报和历史数据)来作为算法程序的输入. 项目的甲方已经购买了天气数据, 依照他们的约定,天气数据的供应商会将数据以"文本" (.TXT)的方式发到F ...

  8. lambda架构简介

    1.Lambda架构背景介绍 Lambda架构是由Storm的作者Nathan Marz提出的一个实时大数据处理框架.Marz在Twitter工作期间开发了著名的实时大数据处理框架Storm,Lamb ...

  9. python-ini文件使用(读和写)

    注意事项: 1.读文件: read(filename):读取ini文件中的内容 sections():得到所有section,返回列表形式 options(section):得到给定section的所 ...

  10. 并发包学习(一)-Atomic包小记

    此篇是J.U.C学习的第一篇Atomic包相关的内容,希望此篇总结能对自己的基础有所提升.本文总结来源自<Java并发编程的艺术>第七章并配以自己的实践理解.如有错误还请指正. 一.案例分 ...