Redis使用JDK序列化可以通過以下步驟進行:
首先,確保你已經導入Redis的Java客戶端庫,比如Jedis。
創建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();
請注意,使用JDK序列化要求被序列化的對象必須實現Serializable接口。在上述示例中,User類需要實現Serializable接口才能進行序列化和反序列化操作。