Redis使用JDK序列化可以通過(guò)以下步驟進(jìn)行:
首先,確保你已經(jīng)導(dǎo)入Redis的Java客戶端庫(kù),比如Jedis。
創(chuàng)建Redis連接:
Jedis jedis = new Jedis("localhost", 6379);
User user = new User("John", 25);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(user);
byte[] serializedUser = outputStream.toByteArray();
jedis.set("user", serializedUser);
byte[] serializedUser = jedis.get("user");
ByteArrayInputStream inputStream = new ByteArrayInputStream(serializedUser);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
User user = (User) objectInputStream.readObject();
jedis.close();
請(qǐng)注意,使用JDK序列化要求被序列化的對(duì)象必須實(shí)現(xiàn)Serializable接口。在上述示例中,User類需要實(shí)現(xiàn)Serializable接口才能進(jìn)行序列化和反序列化操作。