admin vor 1 Jahr
Ursprung
Commit
226905d728

+ 6 - 0
rmi/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+  </component>
+</project>

+ 126 - 0
serializableJava/pom.xml

@@ -0,0 +1,126 @@
+<?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>serializableJava</artifactId>
+    <version>1.0-SNAPSHOT</version>
+
+    <properties>
+        <maven.compiler.source>8</maven.compiler.source>
+        <maven.compiler.target>8</maven.compiler.target>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.2.2.RELEASE</version>
+    </parent>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-context-support</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+            <version>2.5.3</version>
+        </dependency>
+
+        <dependency>
+            <groupId>io.protostuff</groupId>
+            <artifactId>protostuff-runtime</artifactId>
+            <version>1.4.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.google.protobuf</groupId>
+            <artifactId>protobuf-java</artifactId>
+            <version>3.5.1</version>
+        </dependency>
+        <dependency>
+            <groupId>io.protostuff</groupId>
+            <artifactId>protostuff-core</artifactId>
+            <version>1.4.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.caucho</groupId>
+            <artifactId>hessian</artifactId>
+            <version>4.0.63</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.esotericsoftware</groupId>
+            <artifactId>kryo</artifactId>
+            <version>5.2.0</version>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+
+        <extensions>
+            <extension>
+                <groupId>kr.motd.maven</groupId>
+                <artifactId>os-maven-plugin</artifactId>
+                <version>1.5.0.Final</version>
+            </extension>
+        </extensions>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.8</source>
+                    <target>1.8</target>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.xolstice.maven.plugins</groupId>
+                <artifactId>protobuf-maven-plugin</artifactId>
+                <version>0.5.0</version>
+                <configuration>
+                    <protocArtifact>
+                        com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}
+                    </protocArtifact>
+                    <pluginId>grpc-java</pluginId>
+                </configuration>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>compile</goal>
+                            <goal>compile-custom</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>

+ 32 - 0
serializableJava/src/main/java/org/example/KryoSerialization.java

@@ -0,0 +1,32 @@
+package org.example;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.io.Output;
+import java.io.*;
+
+/** Kryo 类会自动执行序列化。Output 类和 Input 类负责处理缓冲字节,并写入到流中。
+ *
+ */
+public class KryoSerialization {
+    static public void main(String[] args) throws Exception {
+        Kryo kryo = new Kryo();
+        kryo.register(SomeClass.class);
+
+        SomeClass object = new SomeClass();
+        object.value = "Hello Kryo!";
+
+        Output output = new Output(new FileOutputStream("file.bin"));
+        kryo.writeObject(output, object);
+        output.close();
+
+        Input input = new Input(new FileInputStream("file.bin"));
+        SomeClass object2 = kryo.readObject(input, SomeClass.class);
+        input.close();
+        System.out.println(object2.value);
+    }
+
+    static public class SomeClass {
+        String value;
+    }
+}

+ 32 - 0
serializableJava/src/main/java/org/example/hessianSerialization/HessianSerializer.java

@@ -0,0 +1,32 @@
+package org.example.hessianSerialization;
+
+import com.caucho.hessian.io.HessianInput;
+import com.caucho.hessian.io.HessianOutput;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class HessianSerializer {
+    public static void main(String[] args) throws IOException {
+        User user=new User();
+        user.setName("Mic");
+        user.setAge(18);
+        byte[] bytes=serializer(user);
+        System.out.println("序列化完成");
+        User nuser=deserializer(bytes);
+        System.out.println(nuser);
+    }
+
+    private static byte[] serializer(User user) throws IOException {
+        ByteArrayOutputStream bos=new ByteArrayOutputStream(); //表示输出到内存的实现
+        HessianOutput ho=new HessianOutput(bos);
+        ho.writeObject(user);
+        return bos.toByteArray();
+    }
+    private static User deserializer(byte[] data) throws IOException {
+        ByteArrayInputStream bis=new ByteArrayInputStream(data);
+        HessianInput hi=new HessianInput(bis);
+        return (User)hi.readObject();
+    }
+}

+ 43 - 0
serializableJava/src/main/java/org/example/hessianSerialization/User.java

@@ -0,0 +1,43 @@
+package org.example.hessianSerialization;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonSetter;
+
+import java.io.Serializable;
+import java.util.Date;
+
+public class User implements Serializable {
+    private String name;
+    private Integer age;
+    private Date birthday;
+    private String email;
+    public String getName() {
+        return name;
+    }
+    public void setName(String name) {
+        this.name = name;
+    }
+    public Integer getAge() {
+        return age;
+    }
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+    public Date getBirthday() {
+        return birthday;
+    }
+    public void setBirthday(Date birthday) {
+        this.birthday = birthday;
+    }
+    public String getEmail() {
+        return email;
+    }
+    public void setEmail(String email) {
+        this.email = email;
+    }
+    @Override
+    public String toString() {
+        return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + ", email=" + email + "]";
+    }
+
+}

+ 55 - 0
serializableJava/src/main/java/org/example/jacksonSerializable/JsonUtils.java

@@ -0,0 +1,55 @@
+package org.example.jacksonSerializable;
+
+import java.io.IOException;
+import java.util.List;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+// JSON/对象转换类
+public class JsonUtils {
+
+    // 定义jackson对象
+    private static ObjectMapper MAPPER=new ObjectMapper();
+
+    // 将对象转换成json字符串
+    public static String objectToJson(Object obj){
+        try {
+            String str=MAPPER.writeValueAsString(obj);
+            return str;
+        } catch (JsonProcessingException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    // 将json数据转换成pojo对象
+    public static <T> T jsonToObject(String json,Class<T> beanType){
+        try {
+            T t=MAPPER.readValue(json, beanType);
+            return t;
+        } catch (JsonParseException e) {
+            e.printStackTrace();
+        } catch (JsonMappingException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    // 将json数据转换成pojo对象list
+    public static <T> List<T> jsonToList(String json,Class<T> beanType){
+        JavaType javaType=MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
+        try{
+            List<T> list=MAPPER.readValue(json, javaType);
+            return list;
+        }catch(Exception e){
+            e.printStackTrace();
+        }
+        return null;
+    }
+}

+ 31 - 0
serializableJava/src/main/java/org/example/jacksonSerializable/Main.java

@@ -0,0 +1,31 @@
+package org.example.jacksonSerializable;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Main {
+    public static void main(String[] args) throws ParseException {
+        List<User> users = new ArrayList<User>();
+        for (int i = 0; i < 20; i++) {
+            User user = new User();
+            user.setName("Apple" + i);
+            user.setAge(20 + i);
+            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
+            user.setBirthday(dateformat.parse("1991-10-01"));
+            user.setEmail("12345678" + i + "@qq.com");
+
+            //  序列化单个对象
+            String json=JsonUtils.objectToJson(user);
+            System.out.println(json);
+
+            users.add(user);
+        }
+
+        // 序列化对象列表
+        String json1 = JsonUtils.objectToJson(users);
+        System.out.println(json1);
+
+    }
+}

+ 44 - 0
serializableJava/src/main/java/org/example/jacksonSerializable/User.java

@@ -0,0 +1,44 @@
+package org.example.jacksonSerializable;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonSetter;
+
+import java.util.Date;
+
+public class User {
+    private String name;
+    private Integer age;
+    private Date birthday;
+    @JsonIgnore
+    private String email;
+    public String getName() {
+        return name;
+    }
+    @JsonSetter("username")
+    public void setName(String name) {
+        this.name = name;
+    }
+    public Integer getAge() {
+        return age;
+    }
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+    public Date getBirthday() {
+        return birthday;
+    }
+    public void setBirthday(Date birthday) {
+        this.birthday = birthday;
+    }
+    public String getEmail() {
+        return email;
+    }
+    public void setEmail(String email) {
+        this.email = email;
+    }
+    @Override
+    public String toString() {
+        return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + ", email=" + email + "]";
+    }
+
+}

+ 13 - 0
serializableJava/src/main/java/org/example/protoBuf/Message.java

@@ -0,0 +1,13 @@
+package org.example.protoBuf;
+
+import lombok.Data;
+
+import java.io.Serializable;
+@Data
+public class Message implements Serializable {
+
+    private String msg; //消息内容
+    private Integer type; //消息类型
+    private double lon; //经度
+    private double lat; //纬度
+}

+ 852 - 0
serializableJava/src/main/java/org/example/protoBuf/MessageBuf.java

@@ -0,0 +1,852 @@
+// Generated by the protocol buffer compiler.  DO NOT EDIT!
+// source: Message.proto
+
+package org.example.protoBuf;
+
+public final class MessageBuf {
+  private MessageBuf() {}
+  public static void registerAllExtensions(
+      com.google.protobuf.ExtensionRegistryLite registry) {
+  }
+
+  public static void registerAllExtensions(
+      com.google.protobuf.ExtensionRegistry registry) {
+    registerAllExtensions(
+        (com.google.protobuf.ExtensionRegistryLite) registry);
+  }
+  public interface MessageOrBuilder extends
+      // @@protoc_insertion_point(interface_extends:Message)
+      com.google.protobuf.MessageOrBuilder {
+
+    /**
+     * <pre>
+     *消息内容
+     * </pre>
+     *
+     * <code>optional string msg = 1;</code>
+     */
+    String getMsg();
+    /**
+     * <pre>
+     *消息内容
+     * </pre>
+     *
+     * <code>optional string msg = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getMsgBytes();
+
+    /**
+     * <pre>
+     *消息类型
+     * </pre>
+     *
+     * <code>optional int64 type = 2;</code>
+     */
+    long getType();
+
+    /**
+     * <pre>
+     *经度
+     * </pre>
+     *
+     * <code>optional double lon = 3;</code>
+     */
+    double getLon();
+
+    /**
+     * <pre>
+     *纬度
+     * </pre>
+     *
+     * <code>optional double lat = 4;</code>
+     */
+    double getLat();
+  }
+  /**
+   * Protobuf type {@code Message}
+   */
+  public  static final class Message extends
+      com.google.protobuf.GeneratedMessageV3 implements
+      // @@protoc_insertion_point(message_implements:Message)
+      MessageOrBuilder {
+    // Use Message.newBuilder() to construct.
+    private Message(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
+      super(builder);
+    }
+    private Message() {
+      msg_ = "";
+      type_ = 0L;
+      lon_ = 0D;
+      lat_ = 0D;
+    }
+
+    @Override
+    public final com.google.protobuf.UnknownFieldSet
+    getUnknownFields() {
+      return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
+    }
+    private Message(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      this();
+      int mutable_bitField0_ = 0;
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!input.skipField(tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              String s = input.readStringRequireUtf8();
+
+              msg_ = s;
+              break;
+            }
+            case 16: {
+
+              type_ = input.readInt64();
+              break;
+            }
+            case 25: {
+
+              lon_ = input.readDouble();
+              break;
+            }
+            case 33: {
+
+              lat_ = input.readDouble();
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e).setUnfinishedMessage(this);
+      } finally {
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return MessageBuf.internal_static_Message_descriptor;
+    }
+
+    protected FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return MessageBuf.internal_static_Message_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              Message.class, Builder.class);
+    }
+
+    public static final int MSG_FIELD_NUMBER = 1;
+    private volatile Object msg_;
+    /**
+     * <pre>
+     *消息内容
+     * </pre>
+     *
+     * <code>optional string msg = 1;</code>
+     */
+    public String getMsg() {
+      Object ref = msg_;
+      if (ref instanceof String) {
+        return (String) ref;
+      } else {
+        com.google.protobuf.ByteString bs = 
+            (com.google.protobuf.ByteString) ref;
+        String s = bs.toStringUtf8();
+        msg_ = s;
+        return s;
+      }
+    }
+    /**
+     * <pre>
+     *消息内容
+     * </pre>
+     *
+     * <code>optional string msg = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getMsgBytes() {
+      Object ref = msg_;
+      if (ref instanceof String) {
+        com.google.protobuf.ByteString b = 
+            com.google.protobuf.ByteString.copyFromUtf8(
+                (String) ref);
+        msg_ = b;
+        return b;
+      } else {
+        return (com.google.protobuf.ByteString) ref;
+      }
+    }
+
+    public static final int TYPE_FIELD_NUMBER = 2;
+    private long type_;
+    /**
+     * <pre>
+     * 消息类型
+     * </pre>
+     *
+     * <code>optional int64 type = 2;</code>
+     */
+    public long getType() {
+      return type_;
+    }
+
+    public static final int LON_FIELD_NUMBER = 3;
+    private double lon_;
+    /**
+     * <pre>
+     *经度
+     * </pre>
+     *
+     * <code>optional double lon = 3;</code>
+     */
+    public double getLon() {
+      return lon_;
+    }
+
+    public static final int LAT_FIELD_NUMBER = 4;
+    private double lat_;
+    /**
+     * <pre>
+     *纬度
+     * </pre>
+     *
+     * <code>optional double lat = 4;</code>
+     */
+    public double getLat() {
+      return lat_;
+    }
+
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized == 1) return true;
+      if (isInitialized == 0) return false;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      if (!getMsgBytes().isEmpty()) {
+        com.google.protobuf.GeneratedMessageV3.writeString(output, 1, msg_);
+      }
+      if (type_ != 0L) {
+        output.writeInt64(2, type_);
+      }
+      if (lon_ != 0D) {
+        output.writeDouble(3, lon_);
+      }
+      if (lat_ != 0D) {
+        output.writeDouble(4, lat_);
+      }
+    }
+
+    public int getSerializedSize() {
+      int size = memoizedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      if (!getMsgBytes().isEmpty()) {
+        size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, msg_);
+      }
+      if (type_ != 0L) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeInt64Size(2, type_);
+      }
+      if (lon_ != 0D) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeDoubleSize(3, lon_);
+      }
+      if (lat_ != 0D) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeDoubleSize(4, lat_);
+      }
+      memoizedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @Override
+    public boolean equals(final Object obj) {
+      if (obj == this) {
+       return true;
+      }
+      if (!(obj instanceof Message)) {
+        return super.equals(obj);
+      }
+      Message other = (Message) obj;
+
+      boolean result = true;
+      result = result && getMsg()
+          .equals(other.getMsg());
+      result = result && (getType()
+          == other.getType());
+      result = result && (
+          Double.doubleToLongBits(getLon())
+          == Double.doubleToLongBits(
+              other.getLon()));
+      result = result && (
+          Double.doubleToLongBits(getLat())
+          == Double.doubleToLongBits(
+              other.getLat()));
+      return result;
+    }
+
+    @Override
+    public int hashCode() {
+      if (memoizedHashCode != 0) {
+        return memoizedHashCode;
+      }
+      int hash = 41;
+      hash = (19 * hash) + getDescriptorForType().hashCode();
+      hash = (37 * hash) + MSG_FIELD_NUMBER;
+      hash = (53 * hash) + getMsg().hashCode();
+      hash = (37 * hash) + TYPE_FIELD_NUMBER;
+      hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
+          getType());
+      hash = (37 * hash) + LON_FIELD_NUMBER;
+      hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
+          Double.doubleToLongBits(getLon()));
+      hash = (37 * hash) + LAT_FIELD_NUMBER;
+      hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
+          Double.doubleToLongBits(getLat()));
+      hash = (29 * hash) + unknownFields.hashCode();
+      memoizedHashCode = hash;
+      return hash;
+    }
+
+    public static Message parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static Message parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static Message parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static Message parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static Message parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return com.google.protobuf.GeneratedMessageV3
+          .parseWithIOException(PARSER, input);
+    }
+    public static Message parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return com.google.protobuf.GeneratedMessageV3
+          .parseWithIOException(PARSER, input, extensionRegistry);
+    }
+    public static Message parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return com.google.protobuf.GeneratedMessageV3
+          .parseDelimitedWithIOException(PARSER, input);
+    }
+    public static Message parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return com.google.protobuf.GeneratedMessageV3
+          .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
+    }
+    public static Message parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return com.google.protobuf.GeneratedMessageV3
+          .parseWithIOException(PARSER, input);
+    }
+    public static Message parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return com.google.protobuf.GeneratedMessageV3
+          .parseWithIOException(PARSER, input, extensionRegistry);
+    }
+
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder() {
+      return DEFAULT_INSTANCE.toBuilder();
+    }
+    public static Builder newBuilder(Message prototype) {
+      return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() {
+      return this == DEFAULT_INSTANCE
+          ? new Builder() : new Builder().mergeFrom(this);
+    }
+
+    @Override
+    protected Builder newBuilderForType(
+        BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code Message}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
+        // @@protoc_insertion_point(builder_implements:Message)
+        MessageOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return MessageBuf.internal_static_Message_descriptor;
+      }
+
+      protected FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return MessageBuf.internal_static_Message_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                Message.class, Builder.class);
+      }
+
+      // Construct using org.example.protoBuf.MessageBuf.Message.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessageV3
+                .alwaysUseFieldBuilders) {
+        }
+      }
+      public Builder clear() {
+        super.clear();
+        msg_ = "";
+
+        type_ = 0L;
+
+        lon_ = 0D;
+
+        lat_ = 0D;
+
+        return this;
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return MessageBuf.internal_static_Message_descriptor;
+      }
+
+      public Message getDefaultInstanceForType() {
+        return Message.getDefaultInstance();
+      }
+
+      public Message build() {
+        Message result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public Message buildPartial() {
+        Message result = new Message(this);
+        result.msg_ = msg_;
+        result.type_ = type_;
+        result.lon_ = lon_;
+        result.lat_ = lat_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder clone() {
+        return (Builder) super.clone();
+      }
+      public Builder setField(
+          com.google.protobuf.Descriptors.FieldDescriptor field,
+          Object value) {
+        return (Builder) super.setField(field, value);
+      }
+      public Builder clearField(
+          com.google.protobuf.Descriptors.FieldDescriptor field) {
+        return (Builder) super.clearField(field);
+      }
+      public Builder clearOneof(
+          com.google.protobuf.Descriptors.OneofDescriptor oneof) {
+        return (Builder) super.clearOneof(oneof);
+      }
+      public Builder setRepeatedField(
+          com.google.protobuf.Descriptors.FieldDescriptor field,
+          int index, Object value) {
+        return (Builder) super.setRepeatedField(field, index, value);
+      }
+      public Builder addRepeatedField(
+          com.google.protobuf.Descriptors.FieldDescriptor field,
+          Object value) {
+        return (Builder) super.addRepeatedField(field, value);
+      }
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof Message) {
+          return mergeFrom((Message)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(Message other) {
+        if (other == Message.getDefaultInstance()) return this;
+        if (!other.getMsg().isEmpty()) {
+          msg_ = other.msg_;
+          onChanged();
+        }
+        if (other.getType() != 0L) {
+          setType(other.getType());
+        }
+        if (other.getLon() != 0D) {
+          setLon(other.getLon());
+        }
+        if (other.getLat() != 0D) {
+          setLat(other.getLat());
+        }
+        onChanged();
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        Message parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (Message) e.getUnfinishedMessage();
+          throw e.unwrapIOException();
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      private Object msg_ = "";
+      /**
+       * <pre>
+       *消息内容
+       * </pre>
+       *
+       * <code>optional string msg = 1;</code>
+       */
+      public String getMsg() {
+        Object ref = msg_;
+        if (!(ref instanceof String)) {
+          com.google.protobuf.ByteString bs =
+              (com.google.protobuf.ByteString) ref;
+          String s = bs.toStringUtf8();
+          msg_ = s;
+          return s;
+        } else {
+          return (String) ref;
+        }
+      }
+      /**
+       * <pre>
+       *消息内容
+       * </pre>
+       *
+       * <code>optional string msg = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getMsgBytes() {
+        Object ref = msg_;
+        if (ref instanceof String) {
+          com.google.protobuf.ByteString b = 
+              com.google.protobuf.ByteString.copyFromUtf8(
+                  (String) ref);
+          msg_ = b;
+          return b;
+        } else {
+          return (com.google.protobuf.ByteString) ref;
+        }
+      }
+      /**
+       * <pre>
+       *消息内容
+       * </pre>
+       *
+       * <code>optional string msg = 1;</code>
+       */
+      public Builder setMsg(
+          String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  
+        msg_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <pre>
+       *消息内容
+       * </pre>
+       *
+       * <code>optional string msg = 1;</code>
+       */
+      public Builder clearMsg() {
+        
+        msg_ = getDefaultInstance().getMsg();
+        onChanged();
+        return this;
+      }
+      /**
+       * <pre>
+       *消息内容
+       * </pre>
+       *
+       * <code>optional string msg = 1;</code>
+       */
+      public Builder setMsgBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  checkByteStringIsUtf8(value);
+        
+        msg_ = value;
+        onChanged();
+        return this;
+      }
+
+      private long type_ ;
+      /**
+       * <pre>
+       *消息类型
+       * </pre>
+       *
+       * <code>optional int64 type = 2;</code>
+       */
+      public long getType() {
+        return type_;
+      }
+      /**
+       * <pre>
+       *消息类型
+       * </pre>
+       *
+       * <code>optional int64 type = 2;</code>
+       */
+      public Builder setType(long value) {
+        
+        type_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <pre>
+       *消息类型
+       * </pre>
+       *
+       * <code>optional int64 type = 2;</code>
+       */
+      public Builder clearType() {
+        
+        type_ = 0L;
+        onChanged();
+        return this;
+      }
+
+      private double lon_ ;
+      /**
+       * <pre>
+       *经度
+       * </pre>
+       *
+       * <code>optional double lon = 3;</code>
+       */
+      public double getLon() {
+        return lon_;
+      }
+      /**
+       * <pre>
+       *经度
+       * </pre>
+       *
+       * <code>optional double lon = 3;</code>
+       */
+      public Builder setLon(double value) {
+        
+        lon_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <pre>
+       *经度
+       * </pre>
+       *
+       * <code>optional double lon = 3;</code>
+       */
+      public Builder clearLon() {
+        
+        lon_ = 0D;
+        onChanged();
+        return this;
+      }
+
+      private double lat_ ;
+      /**
+       * <pre>
+       *纬度
+       * </pre>
+       *
+       * <code>optional double lat = 4;</code>
+       */
+      public double getLat() {
+        return lat_;
+      }
+      /**
+       * <pre>
+       *纬度
+       * </pre>
+       *
+       * <code>optional double lat = 4;</code>
+       */
+      public Builder setLat(double value) {
+        
+        lat_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <pre>
+       *纬度
+       * </pre>
+       *
+       * <code>optional double lat = 4;</code>
+       */
+      public Builder clearLat() {
+        
+        lat_ = 0D;
+        onChanged();
+        return this;
+      }
+      public final Builder setUnknownFields(
+          final com.google.protobuf.UnknownFieldSet unknownFields) {
+        return this;
+      }
+
+      public final Builder mergeUnknownFields(
+          final com.google.protobuf.UnknownFieldSet unknownFields) {
+        return this;
+      }
+
+
+      // @@protoc_insertion_point(builder_scope:Message)
+    }
+
+    // @@protoc_insertion_point(class_scope:Message)
+    private static final Message DEFAULT_INSTANCE;
+    static {
+      DEFAULT_INSTANCE = new Message();
+    }
+
+    public static Message getDefaultInstance() {
+      return DEFAULT_INSTANCE;
+    }
+
+    private static final com.google.protobuf.Parser<Message>
+        PARSER = new com.google.protobuf.AbstractParser<Message>() {
+      public Message parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+          return new Message(input, extensionRegistry);
+      }
+    };
+
+    public static com.google.protobuf.Parser<Message> parser() {
+      return PARSER;
+    }
+
+    @Override
+    public com.google.protobuf.Parser<Message> getParserForType() {
+      return PARSER;
+    }
+
+    public Message getDefaultInstanceForType() {
+      return DEFAULT_INSTANCE;
+    }
+
+  }
+
+  private static final com.google.protobuf.Descriptors.Descriptor
+    internal_static_Message_descriptor;
+  private static final 
+    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
+      internal_static_Message_fieldAccessorTable;
+
+  public static com.google.protobuf.Descriptors.FileDescriptor
+      getDescriptor() {
+    return descriptor;
+  }
+  private static  com.google.protobuf.Descriptors.FileDescriptor
+      descriptor;
+  static {
+    String[] descriptorData = {
+      "\n\rMessage.proto\">\n\007Message\022\013\n\003msg\030\001 \001(\t\022" +
+      "\014\n\004type\030\002 \001(\003\022\013\n\003lon\030\003 \001(\001\022\013\n\003lat\030\004 \001(\001B" +
+      "\"\n\024org.example.protoBufB\nMessageBufb\006pro" +
+      "to3"
+    };
+    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
+          public com.google.protobuf.ExtensionRegistry assignDescriptors(
+              com.google.protobuf.Descriptors.FileDescriptor root) {
+            descriptor = root;
+            return null;
+          }
+        };
+    com.google.protobuf.Descriptors.FileDescriptor
+      .internalBuildGeneratedFileFrom(descriptorData,
+        new com.google.protobuf.Descriptors.FileDescriptor[] {
+        }, assigner);
+    internal_static_Message_descriptor =
+      getDescriptor().getMessageTypes().get(0);
+    internal_static_Message_fieldAccessorTable = new
+      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
+        internal_static_Message_descriptor,
+        new String[] { "Msg", "Type", "Lon", "Lat", });
+  }
+
+  // @@protoc_insertion_point(outer_class_scope)
+}

+ 67 - 0
serializableJava/src/main/java/org/example/protoBuf/ProtoBufUtil.java

@@ -0,0 +1,67 @@
+package org.example.protoBuf;
+
+import io.protostuff.LinkedBuffer;
+import io.protostuff.ProtostuffIOUtil;
+import io.protostuff.Schema;
+import io.protostuff.runtime.RuntimeSchema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.objenesis.Objenesis;
+import org.springframework.objenesis.ObjenesisStd;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * ProtoBufUtil 转换工具类
+ *
+ */
+public class ProtoBufUtil {
+    private static Logger log = LoggerFactory.getLogger(ProtoBufUtil.class);
+    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
+
+    private static Objenesis objenesis = new ObjenesisStd(true);
+
+    @SuppressWarnings("unchecked")
+    private static <T> Schema<T> getSchema(Class<T> cls) {
+        Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
+        if (schema == null) {
+            schema = RuntimeSchema.createFrom(cls);
+            if (schema != null) {
+                cachedSchema.put(cls, schema);
+            }
+        }
+        return schema;
+    }
+
+    public ProtoBufUtil() {
+    }
+
+    @SuppressWarnings({"unchecked"})
+    public static <T> byte[] serializer(T obj) {
+        Class<T> cls = (Class<T>) obj.getClass();
+        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
+        try {
+            Schema<T> schema = getSchema(cls);
+            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
+        } catch (Exception e) {
+            log.error("protobuf序列化失败");
+            throw new IllegalStateException(e.getMessage(), e);
+        } finally {
+            buffer.clear();
+        }
+    }
+
+    public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
+        try {
+            T message = (T) objenesis.newInstance(clazz);
+            Schema<T> schema = getSchema(clazz);
+            ProtostuffIOUtil.mergeFrom(bytes, message, schema);
+            return message;
+        } catch (Exception e) {
+            log.error("protobuf反序列化失败");
+            throw new IllegalStateException(e.getMessage(), e);
+        }
+    }
+
+}

+ 13 - 0
serializableJava/src/main/proto/Message.proto

@@ -0,0 +1,13 @@
+syntax = "proto3";
+
+option java_package = "org.example.protoBuf";//包名
+option java_outer_classname = "MessageBuf";//类名
+
+
+message Message {
+    string msg = 1; //消息内容
+    int64 type = 2; //消息类型
+    double lon = 3; //经度
+    double lat = 4; //纬度
+
+}

+ 45 - 0
serializableJava/src/test/java/Test.java

@@ -0,0 +1,45 @@
+import com.google.protobuf.InvalidProtocolBufferException;
+import org.example.protoBuf.Message;
+import org.example.protoBuf.MessageBuf;
+import org.example.protoBuf.ProtoBufUtil;
+
+
+public class Test {
+    /**
+     * message xxx {
+     * // 字段规则:required -> 字段只能也必须出现 1 次
+     * // 字段规则:optional -> 字段可出现 0 次或1次
+     * // 字段规则:repeated -> 字段可出现任意多次(包括 0)
+     * // 类型:int32、int64、sint32、sint64、string、32-bit ....
+     * // 字段编号:0 ~ 536870911(除去 19000 到 19999 之间的数字)
+     * 字段规则 类型 名称 = 字段编号;
+     * }
+     *
+     * @param args
+     */
+    public static void main(String[] args) throws InvalidProtocolBufferException {
+        /**
+         * 创建.proto文件,定义数据结构
+         */
+        Message message = new Message();
+        message.setLat(12.22);
+        message.setLon(23.22);
+        message.setMsg("你好!");
+        message.setType(1);
+        //序列化message对象,进行传输使用
+        byte[] serializer = ProtoBufUtil.serializer(message);
+        //通过解析字节,转化为buf对象
+        MessageBuf.Message messageBuf = MessageBuf.Message.parseFrom(serializer);
+        //再通过buf对象转化成使用对象message
+        Message messageNow = new Message();
+        messageNow.setType((int)messageBuf.getType());
+        messageNow.setMsg(messageBuf.getMsg());
+        messageNow.setLon(messageBuf.getLon());
+        messageNow.setLat(messageBuf.getLat());
+        System.out.println(messageNow);
+        //直接利用protobuf的工具类反序列化
+        Message deserializer = ProtoBufUtil.deserializer(serializer, Message.class);
+        System.out.println(deserializer);
+
+    }
+}