1. 程式人生 > >Redis寫入和讀取物件資料

Redis寫入和讀取物件資料

Redis由於存入的資料型別有限,一般主要為字串,通過key-value來儲存資料,那麼怎麼通過Redis來寫入和讀取物件資訊呢

寫入資料

1.json方式

該方式使用Gson工具把物件轉為字串

 static void write(){
      //建立連線Redis的物件
    	Jedis jedis = new Jedis("localhost",6379);
    	//設定密碼
    	jedis.auth("123");
    	//新建物件集合,實際專案中為資料庫查到的常用但實時性不強的資訊,作為快取存入redis
    	List<User>
list = new ArrayList<>(); list.add(new User(1, "tom", "tom")); list.add(new User(2, "jack", "jack")); list.add(new User(3, "lilei", "lilei")); //新建Gson 物件,需要導Gson包 Gson gson = new Gson(); //轉json字串 String json = gson.toJson(list); //往redis中放入資料,詳細可參考Redis操作文件
jedis.set("list", json); //釋放 jedis.close(); }

序列化方式,物件需要實現Serializable介面

 static void write2() {
    	try {
    		Jedis jedis = new Jedis("localhost",6379);
        	jedis.auth("123");
        	List<User> list = new ArrayList<>();
        	list.add(new User(1, "tom"
, "tom")); list.add(new User(2, "jack", "jack")); list.add(new User(3, "lilei", "lilei")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(list); byte[] b = bos.toByteArray(); jedis.set("xlist".getBytes(), b); jedis.close(); } catch (Exception e) { // TODO: handle exception } }

讀取資料

1.讀取json資料

   static void read(){
    	Jedis jedis = new Jedis("localhost",6379);
    	jedis.auth("123");
    	Gson gson = new Gson();
    	//讀取存入redis中的key為list的資料
    	String string = jedis.get("list");
      //轉化簡單資料
      // User user = gson.fromJson(string,User.class);
    	//將讀取到的json字串轉化為list集合
    	List<User> list = gson.fromJson(string,new TypeToken<List<User>>(){}.getType());
    	for (User user : list) {
			System.out.println("姓名:"+user.getUname());
		}
    	jedis.close();	
    }

2.序列化方式讀

 static void read2() {
    	try {
    		Jedis jedis = new Jedis("localhost",6379);
        	jedis.auth("123");
        	byte[] b = jedis.get("xlist".getBytes());
            ByteArrayInputStream bis = new ByteArrayInputStream(b);
            ObjectInputStream ois = new ObjectInputStream(bis);
            List<User> list = (List<User>) ois.readObject();
            for (User user : list) {
				System.out.println(user.getUname());
			}
        	jedis.close();
		} catch (Exception e) {
			// TODO: handle exception
		}		
    }