對象序列化:將對象的狀態信息持久保存的過程。 注意:序列化的類型,必須實現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);
}