当前位置: 首页 > article >正文

protostuff序列化方式学习

写在前面

本文看下protostuff序列化机制。
谷歌开发,基于protobuf,性能更优,长江后浪推前浪啦。

1:正文

pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>protostuff</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>io.protostuff</groupId>
            <artifactId>protostuff-core</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.protostuff</groupId>
            <artifactId>protostuff-runtime</artifactId>
            <version>1.6.0</version>
        </dependency>
    </dependencies>
</project>

要序列化的类:

package protostuff;

import java.util.List;

public class School {
    private  String schoolName;
    private List<Student> students;
    public School(String schoolName, List<Student> students) {
        this.schoolName = schoolName;
        this.students = students;
    }
    //getter和setter方法
    //toString方法


    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "School{" +
                "schoolName='" + schoolName + '\'' +
                ", students=" + students +
                '}';
    }
}
package protostuff;

public class Student {
    private  String name;
    private  int    age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

序列化的工具类:

package protostuff;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ProtostuffUtils {
    //避免每次序列化都重新申请Buffer空间
    private static LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    //缓存Schema
    private static Map<Class<?>, Schema<?>> schemaCache = new ConcurrentHashMap<Class<?>, Schema<?>>();

    //序列化方法,把指定对象序列化成字节数组
    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        Class<T> clazz = (Class<T>) obj.getClass();
        Schema<T> schema = getSchema(clazz);
        byte[] data;
        try {
            data = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } finally {
            buffer.clear();
        }
        return data;
    }

    //反序列化方法,将字节数组反序列化成指定Class类型
    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        Schema<T> schema = getSchema(clazz);
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, obj, schema);
        return obj;
    }

    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> clazz) {
        Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
        if (schema == null) {
            schema = RuntimeSchema.getSchema(clazz);
            if (schema == null) {
                schemaCache.put(clazz, schema);
            }
        }
        return schema;
    }
}

测试类:

package protostuff;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        Student stu1 = new Student("张三",20);
        Student stu2 = new Student("李四",21);
        List<Student> students = new ArrayList<Student>();
        students.add(stu1);
        students.add(stu2);
        School school = new School("西工大",students);
        //首先是序列化
        byte[] bytes = ProtostuffUtils.serialize(school);
        System.out.println("序列化后: " + bytes.length);
        //然后是反序列化
        School group1 = ProtostuffUtils.deserialize(bytes,School.class);
        System.out.println("反序列化后: " + school.toString());
    }
}

运行:

序列化后: 35
反序列化后: School{schoolName='西工大', students=[Student{name='张三', age=20}, Student{name='李四', age=21}]}

Process finished with exit code 0

写在后面

参考文章列表

java序列化机制之protoStuff 。


http://www.kler.cn/a/282533.html

相关文章:

  • outline 分析
  • 【计算机网络】TCP网络特点2
  • [JAVA]有关MyBatis环境配置介绍
  • Dubbo 3.2 源码导读
  • centos rich 美观打印日志
  • 二叉树遍历的非递归实现和复杂度分析
  • 第一个go程序
  • matlab实现模拟退火算法
  • 不确定性环境下的自动驾驶汽车行为决策方法
  • 全能型与专精型AI模型:平衡的艺术
  • 【WPF】WPF学习之面试常问问题
  • Windows10系统中安装Maven 3.8.8的步骤
  • 第T10周:使用TensorFlow实现数据增强
  • 【赵渝强老师】使用Docker Machine远程管理Docker
  • 第42篇 使用数码管实现计数器<三>
  • TCP、HTTP以及RPC的梳理
  • Python将Word文档转为PDF
  • npm报错信息集合——基础积累
  • vue3如何监听reactive对象是哪个属性发生的变化
  • 东华医疗协同办公系统templateFile接口存在任意文件读取漏洞 附POC
  • 我的电脑/资源管理器里无法显示新硬盘?
  • Lua收集请求日志
  • 全栈程序员 | 精通安卓、鸿蒙,小程序,Java、Vue.js、SpringBoot及更多技术
  • Git之1.7版本重要特性及用法实例(五十五)
  • 今日算法:蓝桥杯基础题之“微生物增殖”
  • 网络安全面试经验80篇