package com.cn.core;

import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
/**
* 自定义序列化接口
*/
public abstract class Serializer { public static final Charset CHARSET = Charset.forName("UTF-8"); protected ChannelBuffer writeBuffer; protected ChannelBuffer readBuffer; /**
* 反序列化具体实现
*/
protected abstract void read(); /**
* 序列化具体实现
*/
protected abstract void write(); /**
* 从byte数组获取数据
*/
public Serializer readFromBytes(byte[] bytes) {
readBuffer = BufferFactory.getBuffer(bytes);
read();
readBuffer.clear();
return this;
} /**
* 从buff获取数据
*/
public void readFromBuffer(ChannelBuffer readBuffer) {
this.readBuffer = readBuffer;
read();
} /**
* 写入本地buff
*/
public ChannelBuffer writeToLocalBuff(){
writeBuffer = BufferFactory.getBuffer();
write();
return writeBuffer;
} /**
* 写入目标buff
*/
public ChannelBuffer writeToTargetBuff(ChannelBuffer buffer){
writeBuffer = buffer;
write();
return writeBuffer;
} /**
* 返回buffer数组
*/
public byte[] getBytes() {
writeToLocalBuff();
byte[] bytes = null;
if (writeBuffer.writerIndex() == 0) {
bytes = new byte[0];
} else {
bytes = new byte[writeBuffer.writerIndex()];
writeBuffer.readBytes(bytes);
}
writeBuffer.clear();
return bytes;
} public byte readByte() {
return readBuffer.readByte();
} public short readShort() {
return readBuffer.readShort();
} public int readInt() {
return readBuffer.readInt();
} public long readLong() {
return readBuffer.readLong();
} public float readFloat() {
return readBuffer.readFloat();
} public double readDouble() {
return readBuffer.readDouble();
} public String readString() {
int size = readBuffer.readShort();
if (size <= 0) {
return "";
} byte[] bytes = new byte[size];
readBuffer.readBytes(bytes); return new String(bytes, CHARSET);
} public <T> List<T> readList(Class<T> clz) {
List<T> list = new ArrayList<>();
int size = readBuffer.readShort();
for (int i = 0; i < size; i++) {
list.add(read(clz));
}
return list;
} public <K,V> Map<K,V> readMap(Class<K> keyClz, Class<V> valueClz) {
Map<K,V> map = new HashMap<>();
int size = readBuffer.readShort();
for (int i = 0; i < size; i++) {
K key = read(keyClz);
V value = read(valueClz);
map.put(key, value);
}
return map;
} @SuppressWarnings("unchecked")
public <I> I read(Class<I> clz) {
Object t = null;
if ( clz == int.class || clz == Integer.class) {
t = this.readInt();
} else if (clz == byte.class || clz == Byte.class){
t = this.readByte();
} else if (clz == short.class || clz == Short.class){
t = this.readShort();
} else if (clz == long.class || clz == Long.class){
t = this.readLong();
} else if (clz == float.class || clz == Float.class){
t = readFloat();
} else if (clz == double.class || clz == Double.class){
t = readDouble();
} else if (clz == String.class ){
t = readString();
} else if (Serializer.class.isAssignableFrom(clz)){
try {
byte hasObject = this.readBuffer.readByte();
if(hasObject == 1){
Serializer temp = (Serializer)clz.newInstance();
temp.readFromBuffer(this.readBuffer);
t = temp;
}else{
t = null;
}
} catch (Exception e) {
e.printStackTrace();
} } else {
throw new RuntimeException(String.format("不支持类型:[%s]", clz));
}
return (I) t;
} public Serializer writeByte(Byte value) {
writeBuffer.writeByte(value);
return this;
} public Serializer writeShort(Short value) {
writeBuffer.writeShort(value);
return this;
} public Serializer writeInt(Integer value) {
writeBuffer.writeInt(value);
return this;
} public Serializer writeLong(Long value) {
writeBuffer.writeLong(value);
return this;
} public Serializer writeFloat(Float value) {
writeBuffer.writeFloat(value);
return this;
} public Serializer writeDouble(Double value) {
writeBuffer.writeDouble(value);
return this;
} public <T> Serializer writeList(List<T> list) {
if (isEmpty(list)) {
writeBuffer.writeShort((short) 0);
return this;
}
writeBuffer.writeShort((short) list.size());
for (T item : list) {
writeObject(item);
}
return this;
} public <K,V> Serializer writeMap(Map<K, V> map) {
if (isEmpty(map)) {
writeBuffer.writeShort((short) 0);
return this;
}
writeBuffer.writeShort((short) map.size());
for (Entry<K, V> entry : map.entrySet()) {
writeObject(entry.getKey());
writeObject(entry.getValue());
}
return this;
} public Serializer writeString(String value) {
if (value == null || value.isEmpty()) {
writeShort((short) 0);
return this;
} byte data[] = value.getBytes(CHARSET);
short len = (short) data.length;
writeBuffer.writeShort(len);
writeBuffer.writeBytes(data);
return this;
} public Serializer writeObject(Object object) { if(object == null){
writeByte((byte)0);
}else{
if (object instanceof Integer) {
writeInt((int) object);
return this;
} if (object instanceof Long) {
writeLong((long) object);
return this;
} if (object instanceof Short) {
writeShort((short) object);
return this;
} if (object instanceof Byte) {
writeByte((byte) object);
return this;
} if (object instanceof String) {
String value = (String) object;
writeString(value);
return this;
}
if (object instanceof Serializer) {
writeByte((byte)1);
Serializer value = (Serializer) object;
value.writeToTargetBuff(writeBuffer);
return this;
} throw new RuntimeException("不可序列化的类型:" + object.getClass());
} return this;
} private <T> boolean isEmpty(Collection<T> c) {
return c == null || c.size() == 0;
}
public <K,V> boolean isEmpty(Map<K,V> c) {
return c == null || c.size() == 0;
}
} /**
* buff工厂
*/
class BufferFactory {
public static ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN;
/**
* 获取一个buffer
*/
public static ChannelBuffer getBuffer() {
ChannelBuffer dynamicBuffer = ChannelBuffers.dynamicBuffer();
return dynamicBuffer;
}
/**
* 将数据写入buffer
*/
public static ChannelBuffer getBuffer(byte[] bytes) {
ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer(bytes);
return copiedBuffer;
}
}

要序列化的对象:

package com.cn;

import java.util.ArrayList;
import java.util.List; import com.cn.core.Serializer; public class Player extends Serializer{//继承序列化接口,实现read和write接口 private long playerId; private int age; private List<Integer> skills = new ArrayList<>(); private Resource resource = new Resource(); public Resource getResource() {
return resource;
} public void setResource(Resource resource) {
this.resource = resource;
} public long getPlayerId() {
return playerId;
} public void setPlayerId(long playerId) {
this.playerId = playerId;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public List<Integer> getSkills() {
return skills;
} public void setSkills(List<Integer> skills) {
this.skills = skills;
} @Override
protected void read() {
this.playerId = readLong();
this.age = readInt();
this.skills = readList(Integer.class);
this.resource = read(Resource.class);
} @Override
protected void write() {
writeLong(playerId);
writeInt(age);
writeList(skills);
writeObject(resource);
} }
package com.cn;

import com.cn.core.Serializer;

public class Resource extends Serializer {

    private int gold;

    public int getGold() {
return gold;
} public void setGold(int gold) {
this.gold = gold;
} @Override
protected void read() {
this.gold = readInt();
} @Override
protected void write() {
writeInt(gold);
} }
package com.cn;

import java.util.Arrays;

public class Test4 {

    public static void main(String[] args) {

        Player player = new Player();
player.setPlayerId(10001);
player.setAge(22);
player.getSkills().add(101);
player.getResource().setGold(99999); byte[] bytes = player.getBytes(); System.out.println(Arrays.toString(bytes)); //============================================== Player player2 = new Player();
player2.readFromBytes(bytes);
System.out.println(player2.getPlayerId() + " "+player2.getAge() + " "+ Arrays.toString(player2.getSkills().toArray())+" " +player2.getResource().getGold()); } }

netty7---自定义序列化接口的更多相关文章

  1. Java Serializable接口(序列化)理解及自定义序列化

      1 Serializable接口 (1)简单地说,就是可以将一个对象(标志对象的类型)及其状态转换为字节码,保存起来(可以保存在数据库,内存,文件等),然后可以在适当的时候再将其状态恢复(也就是反 ...

  2. .Net Core 自定义序列化格式

    序列化对大家来说应该都不陌生,特别是现在大量使用WEBAPI,JSON满天飞,序列化操作应该经常出现在我们的代码上. 而我们最常用的序列化工具应该就是Newtonsoft.Json,当然你用其它工具类 ...

  3. Newtonsoft.Json高级用法 1.忽略某些属性 2.默认值的处理 3.空值的处理 4.支持非公共成员 5.日期处理 6.自定义序列化的字段名称

    手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...

  4. android ipc通信机制之二序列化接口和Binder

    IPC的一些基本概念,Serializable接口,Parcelable接口,以及Binder.此核心为最后的IBookManager.java类!!! Serializable接口,Parcelab ...

  5. 基础命名空间:序列化_自定义序列化 System.Runtime.Serialization

    (  (From Msdn) 自定义序列化是控制类型的序列化和反序列化的过程,通过控制序列化,可以确保序列化兼容性.换而言之,在不中断类型核心功能的情况下,可在类型的不同版本之间序列化和反序列化. 重 ...

  6. WeihanLi.Redis自定义序列化及压缩方式

    WeihanLi.Redis自定义序列化及压缩方式 Intro WeihanLi.Redis 是基于 StackExchange.Redis 的扩展,提供了一些常用的业务组件和对泛型的更好支持,默认使 ...

  7. Java 自定义序列化、反序列化

    1.如果某个成员变量是敏感信息,不希望序列化到文件/网络节点中,比如说银行密码,或者该成员变量所属的类是不可序列化的, 可以用 transient 关键字修饰此成员变量,序列化时会忽略此成员变量. c ...

  8. 使用Typescript重构axios(二十八)——自定义序列化请求参数

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  9. java自定义序列化

    自定义序列化 1.问题引出 在某些情况下,我们可能不想对于一个对象的所有field进行序列化,例如我们银行信息中的设计账户信息的field,我们不需要进行序列化,或者有些field本省就没有实现Ser ...

随机推荐

  1. iOS开发之--沙盒的操作

    iphone沙箱模型的有四个文件夹,分别是什么,永久数据存储一般放在什么位置,得到模拟器的路径的简单方式是什么. documents,tmp,app,Library. (NSHomeDirectory ...

  2. laravel 配置修改及读取

    1)laravel 的所以配置文件都在根目录下的 config 目录里,直接看一个配置文件的名字就知道是做什么的了,这里不说了 2)读取配置的方法 $value = config('app.timez ...

  3. POI读写大数据量EXCEL

    另一篇文章http://www.cnblogs.com/tootwo2/p/8120053.html里面有xml的一些解释. 大数据量的excel一般都是.xlsx格式的,网上使用POI读写的例子比较 ...

  4. [黑金原创教程] FPGA那些事儿《设计篇 I》- 图像处理前夕

    简介 一本为入门图像处理的入门书,另外还教你徒手搭建平台(片上系统),内容请看目录. 注意 为了达到最好的实验的结果,请准备以下硬件. AX301开发板, OV7670摄像模块, VGA接口显示器, ...

  5. Animate a custom Dialog,自定义Dialog动画

    Inside res/style.xml <style name="AppTheme" parent="android:Theme.Light" /> ...

  6. authz_core_module

    w https://httpd.apache.org/docs/trunk/mod/mod_authz_core.html codeigniter index.html .htaccess <I ...

  7. <2014 12 28> Some conclusions and thought recently

    Since last year August when I started to prepare for the IELTS examiation, it took one year's time f ...

  8. Spring Data 分页和排序 PagingAndSortingRepository的使用(九)

    继承PagingAndSortingRepository 我们可以看到,BlogRepository定义了这样一个方法:Page<Blog> findByDeletedFalse(Page ...

  9. 剑指Offer——和为S的连续正数序列

    题目描述: 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100.但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数).没多久, ...

  10. LeetCode—Minimum Size Subarray Sum

    题目: Given an array of n positive integers and a positive integer s, find the minimal length of a sub ...