protostar/README.md

86 lines
2.5 KiB
Markdown
Raw Normal View History

2020-11-05 10:15:09 +08:00
一款纯粹的Java序列化框架
2020-11-05 10:21:47 +08:00
====================
2020-11-05 10:15:09 +08:00
2020-11-05 10:21:47 +08:00
### 特性
2020-11-05 10:15:09 +08:00
- **纯粹**, 严格按照字节顺序和长度写入,不产生额外的描述性信息;
- **性能**, 基于Netty的ByteBuf可使用池化内存与堆外内存提升性能
- **多版本**, 同一个Class支持多个版本的配置。
### 场景
- 适用于多数序列化场景,用于传输或存储对象;
- 开发初期的目的是为了解析部标、国标相关的通讯协议。
2020-11-03 14:01:20 +08:00
2020-11-05 10:21:47 +08:00
### 使用
2020-11-03 14:01:20 +08:00
```java
2020-11-05 10:15:09 +08:00
public class Test {
public static void main(String[] args) {
//开启序列化过程分析
FieldFactory.EXPLAIN = true;
//获得多个版本的协议定义
Map<Integer, Schema<Foo>> multiVersionSchema = ProtostarUtil.getSchema(Foo.class);
//默认的版本是0
Schema<Foo> schema = multiVersionSchema.get(0);
//使用netty的Unpooled申请初始32字节的空间
ByteBuf buffer = Unpooled.buffer(32);
//将foo写入到缓冲区
schema.writeTo(buffer, foo());
String hex = ByteBufUtil.hexDump(buffer);
System.out.println(hex);
//将缓冲区的字节解析为对象
Foo foo = schema.readFrom(buffer);
System.out.println(foo);
}
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
public static Foo foo() {
Foo foo = new Foo();
foo.setName("张三");
foo.setId(128);
foo.setDateTime(LocalDateTime.of(2020, 7, 7, 19, 23, 59));
return foo;
}
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
public static class Foo {
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
private String name;
private int id;
private LocalDateTime dateTime;
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
@Field(index = 0, type = DataType.STRING, lengthSize = 1, desc = "名称")
public String getName() {
return name;
2020-11-03 14:01:20 +08:00
}
2020-11-05 10:15:09 +08:00
public void setName(String name) {
this.name = name;
}
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
@Field(index = 1, type = DataType.WORD, desc = "ID")
public int getId() {
return id;
}
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
public void setId(int id) {
this.id = id;
}
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
@Field(index = 3, type = DataType.BCD8421, desc = "日期")
public LocalDateTime getDateTime() {
return dateTime;
}
2020-11-03 14:01:20 +08:00
2020-11-05 10:15:09 +08:00
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
}
}
2020-11-03 14:01:20 +08:00
```
2020-11-05 10:37:18 +08:00
### 代码仓库
2021-11-13 17:31:11 +08:00
当前项目是Fork [剑器近](https://gitee.com/yezhihao) 的 [https://gitee.com/yezhihao/protostar/tree/master](https://gitee.com/yezhihao/protostar/tree/master)
2020-11-05 10:15:09 +08:00
更多的例子请参考Test目录