Redis下实现序列化保存和使用FastJson的处理(java)

本文介绍了在引入Redis后,如何处理Java中的数据存储和传输。在不使用Redis时,通常将数据转化为JSON字符串进行处理。加入Redis后,为方便存储List<User>或User等对象,可以封装类或利用FastJson进行序列化和反序列化操作。示例展示了如何使用FastJson将List<News>、User等转换为String,再从String恢复为原对象,简化了与Redis交互的过程。

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"));


至此完毕。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值