从零RPC(四) 实现五种序列化方式及自定义序列化引擎

一、Java默认序列化。接口是自定义的方法很明显,故不再展示。

package com.back.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class DefaultJDKSerializer implements ISerializer {

	public <T> byte[] serialize(T obj) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return baos.toByteArray();
	}

	@SuppressWarnings("unchecked")
	public <T> T deserialize(byte[] data, Class<T> clazz) {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		try {
			ObjectInputStream ois = new ObjectInputStream(bais);
			return (T)ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}

	/**
	 * test successful !
	 * @param args
	 * @throws UnsupportedEncodingException
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		Map map = new HashMap();
		map.put("aa", "bb");
		DefaultJDKSerializer s = new DefaultJDKSerializer();
		byte[] bytes = s.serialize(map);
		System.out.println(new String(bytes,"UTF-8").length());
		
		HashMap map1 = s.deserialize(bytes, HashMap.class);
		
		System.out.println(map1.get("aa"));
	}
}

2、Hessian序列化

package com.back.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/**
  *
  * <p>Title: HessianSerializer</p>  
  * <p>Description: hessian 方式序列化</p>  
  * @author back  
  * @date 2019年8月8日
 */
public class HessianSerializer implements ISerializer{

	public <T> byte[] serialize(T obj) {
		if(null == obj)
			throw new NullPointerException("obj is null");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			HessianOutput ho = new HessianOutput(baos);
			ho.writeObject(obj);
			return baos.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public <T> T deserialize(byte[] data, Class<T> clazz) {
		
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(data);
			HessianInput hi = new HessianInput(bais);
			return (T)hi.readObject();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * test Successful
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Map map = new HashMap();
		map.put("aa", "bb");
		ISerializer s = new HessianSerializer();
		byte[] bytes = s.serialize(map);
		System.out.println(new String(bytes,"UTF-8").length());
		
		HashMap map1 = s.deserialize(bytes, HashMap.class);
		
		System.out.println(map1.get("aa"));
	}
}

三、Json方式

package com.back.serialize;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
  *
  * <p>Title: JsonSerializer</p>  
  * <p>Description:FastJson完成转换 api比较简单 Jackson更强大 易用性低于前者 </p>  
  * @author back  
  * @date 2019年8月8日
 */
public class JsonSerializer implements ISerializer{

	public <T> byte[] serialize(T obj) {
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
		return JSON.toJSONString(obj,SerializerFeature.WriteDateUseDateFormat).getBytes();
	}

	public <T> T deserialize(byte[] data, Class<T> clazz) {
		try {
			return JSON.parseObject(new String(data,"UTF-8"),clazz);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * test Successful
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Map map = new HashMap();
		map.put("aa", "bb");
		ISerializer s = new JsonSerializer();
		byte[] bytes = s.serialize(map);
		System.out.println(new String(bytes,"UTF-8"));
		
		HashMap map1 = s.deserialize(bytes, HashMap.class);
		
		System.out.println(map1.get("aa"));
	}
}

四、Xml方式

package com.back.serialize;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
  *
  * <p>Title: XmlSerializer</p>  
  * <p>Description: 使用XStream完成转换</p>  
  * @author back  
  * @date 2019年8月8日
 */
public class XmlSerializer implements ISerializer{
	
	private final static XStream xStream = new XStream(new DomDriver());

	public <T> byte[] serialize(T obj) {
		return xStream.toXML(obj).getBytes();
	}

	@SuppressWarnings("unchecked")
	public <T> T deserialize(byte[] data, Class<T> clazz) {
	
		try {
			String xml = new String(data,"UTF-8");
			return (T)xStream.fromXML(xml);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) throws Exception {
		Map map = new HashMap();
		map.put("aa", "bb");
		ISerializer s = new XmlSerializer();
		byte[] bytes = s.serialize(map);
		System.out.println(new String(bytes,"UTF-8"));
		
		HashMap map1 = s.deserialize(bytes, HashMap.class);
		
		System.out.println(map1.get("aa"));
	}
}

五、Marshalling方式

package com.back.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;

/**
  *
  * <p>Title: MarshallingSerializer</p>  
  * <p>Description: JBoss - Marshalling 序列化  但是码流好像还很大!</p>  
  * @author back  
  * @date 2019年8月9日
 */
public class MarshallingSerializer implements ISerializer{

	
	final static MarshallingConfiguration config = new MarshallingConfiguration();
	final static MarshallerFactory factory = 
			Marshalling.getProvidedMarshallerFactory("serial");
	public <T> byte[] serialize(T obj) {
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			final Marshaller marshaller = factory.createMarshaller(config);
			marshaller.start(Marshalling.createByteOutput(baos));
			marshaller.writeObject(obj);
			marshaller.finish();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return baos.toByteArray();
	}

	public <T> T deserialize(byte[] data, Class<T> clazz) {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		try {
			final Unmarshaller unMarshaller = factory.createUnmarshaller(config);
			unMarshaller.start(Marshalling.createByteInput(bais));
			return (T)unMarshaller.readObject();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	/**
	 * test Successful
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Map map = new HashMap();
		map.put("aa", "bb");
		ISerializer s = new MarshallingSerializer();
		byte[] bytes = s.serialize(map);
		System.out.println(new String(bytes,"UTF-8"));
		
		HashMap map1 = s.deserialize(bytes, HashMap.class);
		
		System.out.println(map1.get("aa"));
	}
}

六、自定义枚举 完成类型选择

package com.back.constant;

import com.back.serialize.ISerializer;

/**
  *
  * <p>Title: SerializeType  定义我们实现的几种序列化类型</p>  
  * <p>Description: </p>  
  * @author back  
  * @date 2019年8月9日
 */
public enum SerializeType {

	DefaultJDKSerializer("DefaultJDKSerializer"),
	HessianSerializer("HessianSerializer"),
	JsonSerializer("JsonSerializer"),
	XmlSerializer("XmlSerializer"),
	MarshallingSerializer("MarshallingSerializer");

	private String serializeType;

	private SerializeType(String serializeType) {
		this.serializeType = serializeType;
	}
	public String getSerializeType(){
		return this.serializeType;
	}
	
	public static SerializeType queryByType(String type){
		
		if(null == type || "".equals(type))
			return null;
		for (SerializeType serialize : SerializeType.values()) {
			if(type.equals(serialize.getSerializeType())){
				return serialize;
			}
		}
		
		return null;
	}
	
}

 

七、自定义序列化引擎

package com.back.serialize;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.back.constant.SerializeType;
/**
  *
  * <p>Title: SerializeEngine</p>  
  * <p>Description:  序列化引擎 根据支持的方式序列化</p>  
  * @author back  
  * @date 2019年8月9日
 */
public class SerializeEngine {

	public final static Map<SerializeType,ISerializer> map 
				= new ConcurrentHashMap<SerializeType, ISerializer>();

	static{
		map.put(SerializeType.DefaultJDKSerializer, new DefaultJDKSerializer());
		map.put(SerializeType.HessianSerializer, new HessianSerializer());
		map.put(SerializeType.JsonSerializer, new JsonSerializer());
		map.put(SerializeType.XmlSerializer, new XmlSerializer());
		map.put(SerializeType.MarshallingSerializer, new MarshallingSerializer());
	}
	/**
	 * 序列化
	 * @param obj
	 * @param type
	 * @return
	 */
	public static <T> byte[] serialize(T obj , String type){
		SerializeType serialize = SerializeType.queryByType(type);
		if(null == serialize)
			throw new RuntimeException();
		ISerializer iSerializer = map.get(serialize);
		if(null == iSerializer)
			throw new RuntimeException();
		return iSerializer.serialize(obj);
	}
	/**
	 * 反序列化
	 * @param data
	 * @param clazz
	 * @param type
	 * @return
	 */
	public static <T> T deserialize(byte[] data,Class<T> clazz,String type){
		SerializeType serialize = SerializeType.queryByType(type);
		if(null == serialize)
			throw new RuntimeException();
		ISerializer iSerializer = map.get(serialize);
		if(null == iSerializer)
			throw new RuntimeException();
		return iSerializer.deserialize(data, clazz);
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值