redis java对象操作
生活随笔
收集整理的這篇文章主要介紹了
redis java对象操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用Jedis客戶端
1. java 對象,需序列化
public class Person implements Serializable {private int id;private String name;public Person(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public String getName() {return name;}2. 序列化類
public class SerializeUtil {public static byte[] serialize(Object object) {ObjectOutputStream oos = null;ByteArrayOutputStream baos = null;try {// 序列化 baos = new ByteArrayOutputStream();oos = new ObjectOutputStream(baos);oos.writeObject(object);byte[] bytes = baos.toByteArray();return bytes;} catch (Exception e) {}return null;}public static Object unserialize(byte[] bytes) {ByteArrayInputStream bais = null;try {// 反序列化 bais = new ByteArrayInputStream(bytes);ObjectInputStream ois = new ObjectInputStream(bais);return ois.readObject();} catch (Exception e) {}return null;}}3. 對象的操作測試
public class SerializeTest {/*** @param args*/private static Jedis jedis;public static void main(String[] args) throws InterruptedException {jedis=new Jedis("127.0.0.1",6379);setObject();Thread.sleep(1000);Person person =getObject(100);System.out.println(jedis.keys("*"));if(person!=null){System.out.println(person.getId());System.out.println(person.getName()); }delOject();System.out.println(jedis.keys("*"));person = getObject(100);if(person!=null){System.out.println(person.getId());System.out.println(person.getName()); }else{System.out.println("key not exist");}}public static Person getObject(int id) {byte[] person = jedis.get(("person:" + id).getBytes());return (Person) SerializeUtil.unserialize(person);}public static void setObject() {Person person = new Person(100, "alan");jedis.set("person:100".getBytes(), SerializeUtil.serialize(person));person = new Person(101, "bruce");jedis.set("person:101".getBytes(), SerializeUtil.serialize(person));}public static void delOject(){boolean isExist=jedis.exists("person:100".getBytes());if(isExist){System.out.println("delete the key");jedis.del("person:100".getBytes());}}}?
轉載于:https://www.cnblogs.com/davidwang456/p/3229806.html
總結
以上是生活随笔為你收集整理的redis java对象操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单机redis 主从实例
- 下一篇: redis session共享中的序列化