Spring-data-redis: serializer執行個體

來源:互聯網
上載者:User

標籤:ctr   art   序列化   final   inpu   配置   操作   儲存   des   

 

     spring-data-redis提供了多種serializer策略,這對使用jedis的開發人員而言,實在是非常便捷。sdr提供了4種內建的serializer:

  • JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable介面,ObjectInputStrean,ObjectOutputStream),資料以位元組流儲存
  • StringRedisSerializer:字串編碼,資料以string儲存
  • JacksonJsonRedisSerializer:json格式儲存
  • OxmSerializer:xml格式儲存

    其中JdkSerializationRedisSerializer和StringRedisSerializer是最基礎的序列化策略,其中“JacksonJsonRedisSerializer”與“OxmSerializer”都是基於stirng儲存,因此它們是較為“進階”的序列化(最終還是使用string解析以及構建java對象)。

    RedisTemplate中需要聲明4種serializer,預設為“JdkSerializationRedisSerializer”:

    1) keySerializer :對於普通K-V操作時,key採取的序列化策略
    2) valueSerializer:value採取的序列化策略
    3) hashKeySerializer: 在hash資料結構中,hash-key的序列化策略
    4) hashValueSerializer:hash-value的序列化策略

    無論如何,建議key/hashKey採用StringRedisSerializer。

    接下來,通過執行個體描述如何使用它們,可以首先參考“spring-data-redis特性”:

 

一. JdkSerializationRedisSerializer/StringRedisSerializer

    1) spring設定檔

Java代碼  
  1. <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
  2.     <property name="connectionFactory" ref="jedisConnectionFactory"></property>  
  3.     <property name="keySerializer">  
  4.         <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>  
  5.     </property>  
  6.     <property name="hashKeySerializer">  
  7.         <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>  
  8.     </property>  
  9.     <property name="valueSerializer">  
  10.         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  11.     </property>  
  12.     <property name="hashValueSerializer">  
  13.         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  14.     </property>  
  15. </bean>  

    2) 程式執行個體:

Java代碼  
  1. ValueOperations<String, User> valueOper = redisTemplate.opsForValue();  
  2. User user = new User("zhangsan",12);  
  3. valueOper.set("user:1", user);  
  4. System.out.println(valueOper.get("user:1").getName());  

    其中User為pojo類,且需要實現Serializable介面。

 

二.sdr與json

    1) spring配置:

Java代碼  
  1. <bean id="jsonSerializer" class="com.sample.redis.sdr.JsonRedisSerializer"/>  
  2. <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
  3.     <property name="connectionFactory" ref="jedisConnectionFactory"></property>  
  4.     <property name="defaultSerializer">  
  5.         <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>  
  6.     </property>  
  7. </bean>  

    並沒有在設定檔中,使用JacksonJsonRedisSerializer,因為這樣實在是麻煩而且不靈活(主要是jackson需要ClassType)。我們將在java代碼進行轉換,因為通過java代碼,使用jackson工具將json字串轉換成javabean是非常簡單的。

    2) 程式執行個體:

Java代碼  
  1. /** 
  2. * 不使用sdr內建的json序列化工具,一切操作基於string 
  3. **/  
  4. public class JsonRedisSeriaziler{  
  5.     public static final String EMPTY_JSON = "{}";  
  6.       
  7.     public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");  
  8.       
  9.     protected ObjectMapper objectMapper = new ObjectMapper();  
  10.     public JsonRedisSeriaziler(){}  
  11.       
  12.     /** 
  13.      * java-object as json-string 
  14.      * @param object 
  15.      * @return 
  16.      */  
  17.     public String seriazileAsString(Object object){  
  18.         if (object== null) {  
  19.             return EMPTY_JSON;  
  20.         }  
  21.         try {  
  22.             return this.objectMapper.writeValueAsString(object);  
  23.         } catch (Exception ex) {  
  24.             throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);  
  25.         }  
  26.     }  
  27.       
  28.     /** 
  29.      * json-string to java-object 
  30.      * @param str 
  31.      * @return 
  32.      */  
  33.     public <T> T deserializeAsObject(String str,Class<T> clazz){  
  34.         if(str == null || clazz == null){  
  35.             return null;  
  36.         }  
  37.         try{  
  38.             return this.objectMapper.readValue(str, clazz);  
  39.         }catch (Exception ex) {  
  40.             throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);  
  41.         }  
  42.     }  
  43.   
  44. }  
Java代碼  
  1. public class RedisClientTest {  
  2.   
  3.     private JsonRedisSeriaziler seriaziler;  
  4.       
  5.     private RedisTemplate redisTemplate;  
  6.   
  7.     public void setSeriaziler(JsonRedisSeriaziler seriaziler) {  
  8.         this.seriaziler = seriaziler;  
  9.     }  
  10.   
  11.     public void setRedisTemplate(RedisTemplate redisTemplate) {  
  12.         this.redisTemplate = redisTemplate;  
  13.     }  
  14.       
  15.       
  16.     public void insertUser(User user){  
  17.         ValueOperations<String, String> operations = redisTemplate.opsForValue();  
  18.         operations.set("user:" + user.getName(), seriaziler.seriazileAsString(user));  
  19.     }  
  20.       
  21.     public User getUser(String name){  
  22.         ValueOperations<String, String> operations = redisTemplate.opsForValue();  
  23.         String json = operations.get("user:" + name);  
  24.         return seriaziler.deserializeAsObject(json, User.class);  
  25.     }  
  26. }  

三.sdr與xml

    實施辦法可以參見本文“sdr與json”,同時參考spring-oxm相關文檔。

 

Spring-data-redis: serializer執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.