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. C static 关键字理解

    今天来看一下这么一个程序. #include<stdio.h> int count =1; int fun(void) { static int count =10; return cou ...

  2. swift - UIView 设置背景色和背景图片

    代码如下: let page = UIView() page.frame = self.view.bounds //直接设置颜色 page.backgroundColor = UIColor.gree ...

  3. EditText监听方法,实时的判断输入多少字符

    最近在写一个小项目,其中有一点用到了显示EditText中输入了多少个字符,像微博中显示剩余多少字符的功能.在EditText提供了一个方法addTextChangedListener实现对输入文本的 ...

  4. java URL、HTTP与HTML+CSS

    一.Web三大基石 1 二.API(Application Programming Interface,应用程序编程接口) 1 三.题目分析总结: 3 五.HTTP协议与寄信是类似的 6 请求报文 6 ...

  5. HDU 4605 Magic Ball Game(可持续化线段树,树状数组,离散化)

    Magic Ball Game Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) ...

  6. java WebSocket的实现以及Spring WebSocket

    开始学习WebSocket,准备用它来实现一个在页面实时输出log4j的日志以及控制台的日志. 首先知道一些基础信息: java7 开始支持WebSocket,并且只是做了定义,并未实现 tomcat ...

  7. 《Apologize》歌曲

    OneRepublic,中译名“共和时代”,是美国的一个流行摇滚乐队,曲风走流行.独立摇滚的路线.2006年天使专辑<Dreaming Out Loud>诞生,主打<Apologiz ...

  8. NavagationBar 设置颜色和状态栏设置白色

    ios7以下的版本设置导航栏背景颜色可以使用 [[UINavigationBar appearance] setTintColor:[UIColor orangeColor]]; ios7以后: [[ ...

  9. TCP控制位 sendUrgentData 队列 队列元素 优先级 极限 急停 置顶

    Socket (Java Platform SE 7 ) https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#sendUrge ...

  10. 大文本 mysql es

    大文本 mysql  es mysql  id longText  ---> es  longText mysqlId 大文本先入mysql,再同步至es: 文本查询逻辑交由es实现: mysq ...