1. 程式人生 > >Redis下實現序列化儲存和使用FastJson的處理(java)

Redis下實現序列化儲存和使用FastJson的處理(java)

1.在不使用Redis的情況下; 

 我們一般從資料庫中查到資料,然後放進List<User>,或者是User,然後使用java的框架,放資料到指定位置。

或者是從資料庫中查到資料,放到List<User>,然後拼接json字串或使用各種json庫將字串respon回前臺,前臺使用js來解析放到指定位置。

2.加入了Redis後:

從資料庫中查到資料,然後放進List<User>,或者是User,然後將資料存進Redis中,在需要使用時,從Redis中通過鍵獲得值。

但是:java中操作Redis,沒有原生的api能實現:儲存  list<User>,或者是實體類:Redis一般情況下儲存普通的型別的資料,儘管他也能存set,list,等等,但是直接調api還是有很多東西要做的。所以不如封裝一個類,達到將List<User>,或者User這樣的資料存進去,獲取也一下子可以獲取。

 public static class ObjectsTranscoder{
              /**
               * 序列化
               * **/
	        public static  <T> byte[] serialize(List<T> t) {  
	            if (t == null) {
	                throw new NullPointerException("Can't serialize null");
	            }
	            byte[] rv=null;
	            ByteArrayOutputStream bos = null;
	            ObjectOutputStream os = null;
	            try {
	                bos = new ByteArrayOutputStream();
	                os = new ObjectOutputStream(bos);
	                for(T user : t){
	                    os.writeObject(user);
	                }
	                os.writeObject(null);
	                os.close();
	                bos.close();
	                rv = bos.toByteArray();
	            } catch (IOException e) {
	                throw new IllegalArgumentException("Non-serializable object", e);
	            } finally {
	                close(os);
	                close(bos);
	            }
	            return rv;
	        }


	        /**
             * 反序列化
             * **/
	        public static <T> List<T> deserialize(byte[] in) throws IOException {
	            List<T> list = new ArrayList<T>();
	            ByteArrayInputStream bis = null;
	            ObjectInputStream is = null;
	            try {
	                if(in != null) {
	                    bis=new ByteArrayInputStream(in);
	                    is=new ObjectInputStream(bis);
	                    while (true) {
	                        T user = (T) is.readObject();
	                        if(user == null){
	                            break;
	                        }else{
	                            list.add(user);
	                        }
	                    }
	                    is.close();
	                    bis.close();
	                }
	            } catch (IOException e) {
	               
	            } catch (ClassNotFoundException e) {
	           
	            } finally {
	            	is.close();
	            	bis.close();
	               
	            }
	            return list;
	        }
	    }
	    
 static class ListTranscoder{
	        public static byte[] serialize(Object value) throws IOException {
	            if (value == null) {
	                throw new NullPointerException("Can't serialize null");
	            }
	            byte[] rv=null;
	            ByteArrayOutputStream bos = null;
	            ObjectOutputStream os = null;
	            try {
	                bos = new ByteArrayOutputStream();
	                os = new ObjectOutputStream(bos);
	                os.writeObject(value);
	               
	                rv = bos.toByteArray();
	            } catch (IOException e) {
	                throw new IllegalArgumentException("Non-serializable object", e);
	            } finally {
	            	 os.close();
		                bos.close();
	            }
	            return rv;
	        }

	        public static  Object deserialize(byte[] in) throws IOException {
	            Object rv=null;
	            ByteArrayInputStream bis = null;
	            ObjectInputStream is = null;
	            try {
	                if(in != null) {
	                    bis=new ByteArrayInputStream(in);
	                    is=new ObjectInputStream(bis);
	                    rv=is.readObject();
	                    is.close();
	                    bis.close();
	                }
	            } catch (IOException e) {
	               
	            } catch (ClassNotFoundException e) {
	              
	            } finally {
	            	is.close();
	            	bis.close();
	                
	            }
	            return rv;
	        }
	    }


大工告成。

然後還沒完:自己寫也可以,用大牛寫的也可以。阿里巴巴的FastJson也可以解決。很多情況下,我們都會使用返回json資料的形式達到和各種不同客戶端的資料傳遞。所以使用FastJson還是蠻好的。

直接上程式碼吧:

List<News>   --------------->  String  ----------------->List<News>

public void FastJsonList() throws IOException
	{
		Jedis jd=new Jedis("localhost");
		String sql="select * from user where id=?";
		Query query=this.em.createNativeQuery(sql,User.class);
		query.setParameter(1,5);  //第一個引數是多少
		User user=(User) query.getSingleResult();
			List<News> userlist=user.getItems();
			
			String liststr=JSON.toJSONString(userlist);
		jd.set("liststr",liststr);

		List<News> ls=JSON.parseArray(jd.get("liststr"),News.class);
		System.out.println(ls.get(1).getContent());
	}

User            ------------->String      ----------------->User

public void FastJsonsObject() throws IOException
	{
		Jedis jd=new Jedis("localhost");
		String sql="select * from user where id=?";
		Query query=this.em.createNativeQuery(sql,User.class);
		query.setParameter(1,5);  //第一個引數是多少
		User user=(User) query.getSingleResult();
			List<News> userlist=user.getItems();
			
			String liststr=JSON.toJSONString(user);
		jd.set("liststrs",liststr);

		User users=JSON.parseObject(liststr,User.class);
		System.out.println(users.getItems().get(0).getContent());
	}

List<>的String

String   ---------------JSONArray ----------------------->String

JSONArray list=JSON.parseArray(jd.get("liststr"));
			System.out.println(list.getJSONObject(0).get("content").toString());


User的Stirng

String------------>JSONObject-------------------------->String

JSONObject namess=JSON.parseObject(jd.get("names"));
			System.out.println(namess.getString("content"));

至此完畢。