zoukankan      html  css  js  c++  java
  • protobuf

    Plugins安装Protobuf support

    build.gradle(application):

    dependencies {
           classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.8'
    }

    build.gradle(app):

    apply plugin: 'com.google.protobuf'
    android {    
        sourceSets {
            main {
                java {
                    srcDir 'src/main/java'
                }
                proto {
                    srcDir 'src/main/proto'
                }
            }
        }
    }
    protobuf {
        //配置protoc编译器
        protoc {
            artifact = 'com.google.protobuf:protoc:3.5.1'
        }
        //这里配置生成目录,编译后会在build的目录下生成对应的java文件
        generateProtoTasks {
            all().each { task ->
                task.builtins {
                    remove java
                }
                task.builtins {
                    java {}
                }
            }
        }
    }
    
    dependencies {
        implementation 'com.google.protobuf:protobuf-java:3.5.1'
    }

    序列化:

    syntax = "proto3";
    
    option java_package = "com.anny.protobuf";
    option java_outer_classname = "_StudentSerializable";
    
    message _Student{
        string name = 1;
        string sax = 2;
        int32 age = 3;
    
        repeated _Course course = 4;
    }
    
    message _Course{
        string name = 1;
        float score = 2;
    }
    /**
    * protoBuf 用的是变长字节,会压缩数据
    * 按需序列化,特别省空间
    * 其他比如需要填满64位等
    */
        private static _StudentSerializable._Student deSerialize(byte[] bs) {
            try {
                return _StudentSerializable._Student.parseFrom(bs);
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    
        private static byte[] serialize() {
            _StudentSerializable._Course.Builder courseBuilder = _StudentSerializable._Course.newBuilder()
                    .setName("English").setScore(66.6f);
            _StudentSerializable._Student.Builder builder = _StudentSerializable._Student.newBuilder()
                    .setName("Anny").setAge(31).setSax("women").addCourse(courseBuilder);
            _StudentSerializable._Student student = builder.build();
            return student.toByteArray();
        }
  • 相关阅读:
    ASP.NET Boilerplate
    Financial.IPmt/Financial.PPmt
    VB内部函数(三)——财务函数
    Convert VB.NET to C#
    MySQL 使用自增ID主键和UUID 作为主键的优劣比较详细过程(从百万到千万表记录测试)
    Oauth2.0客户端服务端示例
    一张图搞定OAuth2.0
    使用JAVA实现的一个简单IOC注入实例
    谈谈对Spring IOC的理解
    秒懂,Java 注解 (Annotation)你可以这样学
  • 原文地址:https://www.cnblogs.com/anny0920/p/12649348.html
Copyright © 2011-2022 走看看