Redis的序列化和反序列化


對象序列化:將對象的狀態信息持久保存的過程。 注意:序列化的類型,必須實現Serializable接口

對象反序列化:根據對象的狀態信息恢復對象的過程。

在Redis中有2種常用的方式:字節數組和json串****

1.字節數組
添加依賴

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
  <dependency>
     <groupId>org.apache.commons</groupId> 
     <artifactId>commons-lang3</artifactId>
     <version>3.8.1</version>
   </dependency>
 @Test 
public void testJDKSerializer(){
    User user = new User(1, "abc",18,10000.0,new Date());
    //使用commons-lang3中的工具將對象轉換為字節數組
    byte[] bs = SerializationUtils.serialize(user);

    Jedis jedis = JedisUtils.getJedis();
    jedis.set("u".getBytes(), bs);

    byte[] bs2 = jedis.get("u".getBytes());
    //使用commons-lang3中的工具將為字節數組轉換為對象
    User user2 = SerializationUtils.deserialize(bs2);
    System.out.println("user2 = " + user2);

    JedisUtils.close(jedis);
}

json串

<!-- 引入jackson依賴-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.3</version>
</dependency>
@Test
public void testJsonSerializer() throws JsonProcessingException {
    User user = new User(1, "abc",18,10000.0,new Date());
    //使用JSON工具將對象轉換為json字符串
    ObjectMapper mapper = new ObjectMapper();
    String userJson = mapper.writeValueAsString(user);

    Jedis jedis = JedisUtils.getJedis();
    jedis.set("u", userJson);

    String userJson2 = jedis.get("u");

    //使用JSON工具將json字符串轉換為對象
    User user2 = mapper.readValue(userJson2, User.class);
    System.out.println("user2 = " + user2);

    JedisUtils.close(jedis);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM