關(guān)于ProtoBuf枚舉向前兼容問題解決方案

背景

proto來定義和后臺(tái)通信的數(shù)據(jù)模型,并且很多地方使用到了proto的枚舉(enum),但是這個(gè)枚舉的向前兼容性不太好。例如
消息類型定義為:

message CCCBean{
  BEnum b = 1;
}

低版本里面的枚舉只有

enum BEnum {
  a = 0;  b = 1;
}

但是隨著業(yè)務(wù)發(fā)展高版本新增了c=2 和 d=3 的類型

enum BEnum {
  a = 0;  b = 1; c = 2;d = 3;
}

這個(gè)時(shí)候后臺(tái)下發(fā)的數(shù)據(jù)里面帶有BEnum = 3的情況的時(shí)候,就拿不到正確的枚舉類型,切使用以下方式會(huì)拋出異常

例如我們模擬后臺(tái)返回,枚舉為3

val json = "{\"b\":3}"
val newJsonBuilder = TestPbMutile.CCCBean.newBuilder()
JsonFormat.parser().merge(json, newJsonBuilder)
val jsonPb = newJsonBuilder.build()
val value = jsonPb.bValue // 這種方式不會(huì)報(bào)錯(cuò)
val b = jsonPb.b
val enumB = jsonPb.b.number // 這一行會(huì)報(bào)錯(cuò)
image.png

總結(jié)以上分別兩種取值方式
1、

jsonPb.bValue

2、

jsonPb.b.number
第一種不會(huì)報(bào)錯(cuò),第二種會(huì)拋出異常

由此可以思考出以下解決方案,不調(diào)用 proto生成的java類的getEnum().number 方法

其中有思考方案如下

1.添加注解,標(biāo)注廢棄,在項(xiàng)目組內(nèi)同步宣講,避免大家踩坑

2.移除getEnum()方法

2.將getEnum()方法返回值從Enum類型改為int類型

經(jīng)過思考得出

方案1在多人協(xié)同開發(fā)中沒辦法完全避免,總會(huì)有其他同學(xué)踩坑

方案2會(huì)讓pb.toString()的時(shí)候會(huì)拋出異常 ,如下

image.png

最終實(shí)現(xiàn)方案3,將getEnum返回類型改為int

接下來方案3是實(shí)現(xiàn)流程

image.png

這里是jar腳本大致邏輯

image.png

介紹一下jar腳本中使用的框架

1、JavaParser 可以解析java文件,可以獲取其中的類,方法,成員變量等等,也可以方便的添加刪除修改代碼,并且方便的覆蓋掉原文件

依賴

implementation 'com.github.javaparser:javaparser-core:3.23.1'

所用主要功能

a、解析java文件內(nèi)所有class,并輸出名字
// ...
Path path = Paths.get(pbFileName);            
CompilationUnit outCu = StaticJavaParser.parse(path);
List<String> allClassname = ClassNameExtractor.extractFullClassNames(outCu);
// ...

public static List<String> extractFullClassNames(CompilationUnit cu) throws IOException, ParseException {

        List<String> fullClassNames = new ArrayList<>();
        VoidVisitorAdapter<List<String>> classNameCollector = new VoidVisitorAdapter<List<String>>() {
            @Override
            public void visit(ClassOrInterfaceDeclaration n, List<String> arg) {
                super.visit(n, arg);
                arg.add(getFullClassName(n));
            }

            @Override
            public void visit(EnumDeclaration n, List<String> arg) {
                super.visit(n, arg);
                arg.add(getFullClassName(n));

            }

            private String getFullClassName(TypeDeclaration<?> n) {
                String packageName = cu.getPackageDeclaration()
                        .map(PackageDeclaration::getNameAsString)
                        .orElse("");
                String oriClassName = n.getFullyQualifiedName()
                        .orElse(n.getNameAsString());
                oriClassName = oriClassName.replace(".", "$");
                if (!packageName.isEmpty()) {
                    oriClassName = packageName + "." + oriClassName.substring(packageName.length() + 1);
                }
                return oriClassName;
            }
        };

        classNameCollector.visit(cu, fullClassNames);

        return fullClassNames;
    }
b、遍歷類里面的method,找出返回值為枚舉的getXXXEnum方法。將其返回值設(shè)置為int,注意這里要注意oneOf關(guān)鍵字也會(huì)生成Enum需要被過濾掉,看源碼發(fā)現(xiàn)oneOf生成的枚舉實(shí)現(xiàn)于com.google.protobuf.Internal.EnumLite,而 filed為枚舉生成的枚舉實(shí)現(xiàn)于com.google.protobuf.ProtocolMessageEnum,可以用于區(qū)別
for (Method method : clazz.getMethods()) {
    // 將返回值是枚舉類型的方法并且是getXXXEnum方法 改變返回值為int
    if (method.getReturnType().isEnum()&&method.getName().startsWith("get")) {
      // ...
      // 注意,這里過濾oneOf的情況
      boolean needJump = false;
      for (Class<?> anInterface : method.getReturnType().getInterfaces()) {
        if(enumLiteClass.getName().equals(anInterface.getName())){
          needJump = true;
          break;
        }
      }
      if (needJump){
        continue;
      }
      // 標(biāo)記這個(gè)方法,需要被修改 ?。。?!
      //  ... 
    }
}
c、對(duì)method修改,并且覆蓋寫入原文件
for (MethodDeclaration method : classOrInterface.getMethods()) {
  // ...
  // 匹配到需要被修改的方法
  // 將返回枚舉的方法。變成返回int                     
  method.setType(int.class);
  // 修改其方法體內(nèi)容
  method.removeBody();
  Statement statement = StaticJavaParser.parseStatement("return " + method.getNameAsString() + "Value();");
  BlockStmt blockStmt = new BlockStmt();
  blockStmt.addStatement(statement);
  method.setBody(blockStmt);
  // 處理注釋 和 添加注釋
  String oldCommentStr = "";
  Comment oldComment = method.getComment().orElse(null);
  if (oldComment != null) {
    oldCommentStr = oldComment.toString()
      .replaceAll("/\\*\\*", "")
      .replaceAll("/\\*", "")
      .replaceAll("\\*", "")
      .replaceAll("/", "")
      .replaceAll("\\n", "")
      .replaceAll("\\*/", "");
  }
  method.setBlockComment("* \n\t\t* " + oldCommentStr + " \n\t\t* old return type is " + oldReturnType + " now change return type to int \n\t\t");
  // ...
}

// 覆蓋寫入文件
Files.write(path, outCu.toString().getBytes());

2、Compiler可以將java代碼編譯成class文件??梢宰屍浔籧lassLoader所解析。然后就可以通過class相關(guān)api獲取類描述信息

依賴
implementation 'org.codehaus.groovy:groovy-eclipse-compiler:3.6.0-03'

主要功能

a、將java文件編譯為class文件,并輸出到對(duì)應(yīng)目錄
// ...
DynamicCompiler.compile(pbFileName, compilerPath);
// ...

    public static void compile(String sourceFilePath, String outputDirectoryPath) {
        File sourceFile = new File(sourceFilePath);
        File outputDirectory = new File(outputDirectoryPath);

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        try {
            fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputDirectory));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);

        task.call();

        try {
            fileManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

接下來對(duì)比執(zhí)行了jar腳本之后pb生成的java類,生成類代碼太多了,此處就不貼代碼了,只羅列出修改點(diǎn)

注意,一個(gè)pb的message生成類會(huì)生成三個(gè)java類,接下來我舉例說明

pb文件名為testPb.proto,內(nèi)容為

message TestBean{
  int64 id = 1; 
  Sex sex = 2; 
}
enum Sex {
  man = 0;
  female = 1;
}

以下為Java偽代碼,主要是解釋生成類的關(guān)系

public final class TestPb {
    public interface TestBeanOrBuilder extends 
    com.google.protobuf.MessageOrBuilder {
      // <code>int64 id = 1;</code>
      long getId();
      // <code>.com.pb.test.Sex sex = 4;</code>
      int getSexValue();
      // <code>.com.pb.test.Sex sex = 4;</code>
      Sex getSex();
    }
    public  static final class TestBean extends
      com.google.protobuf.GeneratedMessageV3 implements
      TestBeanOrBuilder {
      // ...
       public static final class Builder extends
        com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
        com.pb.test.TestPb.TestBeanOrBuilder {
         // ...
         // ...
       }
      // ... 
    }
}

最外層類名為pb文件名,其中一個(gè)message就對(duì)應(yīng)一個(gè)TestBeanOrBuilder接口 和一個(gè) Bean類,且這個(gè)Bean類里面有一個(gè)內(nèi)部類Builder類

以下三個(gè)類分別簡稱為 數(shù)據(jù)接口、Bean類,BeanBuilder類

1、原類會(huì)返回帶枚舉的值,新類返回值會(huì)變成int (包括 數(shù)據(jù)接口、Bean類,BeanBuilder類)

原類

/** 
* <code>.com.pb.test.Sex sex = 4;</code>
*/
public com.pb.test.TestPb.Sex getSex() {
  com.pb.test.TestPb.Sex result = com.pb.test.TestPb.Sex.valueOf(sex_);
  return result == null ? com.pb.test.TestPb.Sex.UNRECOGNIZED : result;
}

修改后的

//  <code>.com.pb.test.Sex sex = 4;<code>  
// old return type is com.pb.test.TestPb.Sex now change return type to int 
public int getSex() {
  return sex_;
}

2、BeanBuilder類添加 setEnum方法

原類

public  static final class TestBean extends
  com.google.protobuf.GeneratedMessageV3 implements
  TestBeanOrBuilder {
  // <code>.com.pb.test.Sex sex = 4;</code>
  public Builder setSexValue(int value) {
    sex_ = value;
    onChanged();
    return this;
  }
  // <code>.com.pb.test.Sex sex = 4;</code>
  public Builder setSex(com.pb.test.TestPb.Sex value) {
    if (value == null) {
      throw new NullPointerException();
    }
    sex_ = value.getNumber();
    onChanged();
    return this;
  }
    
}

修改類

public  static final class TestBean extends
  com.google.protobuf.GeneratedMessageV3 implements
  TestBeanOrBuilder {
  // <code>.com.pb.test.Sex sex = 4;</code>
  public Builder setSexValue(int value) {
    sex_ = value;
    onChanged();
    return this;
  }
  // <code>.com.pb.test.Sex sex = 4;</code>
  public Builder setSex(com.pb.test.TestPb.Sex value) {
    if (value == null) {
      throw new NullPointerException();
    }
    sex_ = value.getNumber();
    onChanged();
    return this;
  }
  // 新增方法    
  /* 為了兼容 將getEnum方法返回的enum的類型 改成了int,所以需要在build方法中添加對(duì)應(yīng)的set方法*/
  public Builder setSex(int value) {
    sex_ = value;
    onChanged();
    return this;
  }
}

3、在靜態(tài)代碼塊中 遍歷所有filde找到類型為Enum的所有filde,他他們的類型改為int,并且設(shè)置defalutValue為0

static{
  //...
  //這一句就是初始化 getDescriptor()
  Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new Descriptors.FileDescriptor[] {}, assigner);

  //...
}

修改后的類

static{
  //...
  //這一句就是初始化 getDescriptor()
  Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new Descriptors.FileDescriptor[] {}, assigner);
  for (Descriptors.Descriptor messageType : getDescriptor().getMessageTypes()) {
    for (Descriptors.FieldDescriptor field : messageType.getFields()) {
      if (field.getType() == Descriptors.FieldDescriptor.Type.ENUM) {
        Class fieldClass = field.getClass();
        try {
          Field typeField = fieldClass.getDeclaredField("type");
          typeField.setAccessible(true);
          typeField.set(field, Descriptors.FieldDescriptor.Type.INT32);
          Field defaultValueField = fieldClass.getDeclaredField("defaultValue");
          defaultValueField.setAccessible(true);
          defaultValueField.set(field, 0);
        } catch (NoSuchFieldException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        }
      }
    }
  }
  //...
}

被修改的生成pb類,在運(yùn)行過程中的表現(xiàn)

測(cè)試Pb類

message PbA{
  int64 id = 1;
  string name = 2;
  repeated string job = 3;
  Sex sex = 4;
  Sex sex_b_type = 5;
  Sex sex_c_type = 6;
  TypeA type = 7;

  enum TypeA {
    type1 = 0;
    type2 = 1;
    type3 = 2;
  }
}

enum Sex {
  man = 0;
  female = 1;
}

1、pb使用builder初始化和toString()方法,以及取值

image.png

2、pb和bytes相互轉(zhuǎn)換

image.png

3、pb和json相互轉(zhuǎn)換

image.png

可以看出來,修改之后的pb生成類,也可以滿足日常開發(fā)中的業(yè)務(wù)功能,但是由于PB庫很多使用了反射機(jī)制來訪問。所以不排除有一些極少出情況的坑點(diǎn)。如果碰到了歡迎大家留言。

另外如果大家想要看源碼可以去github獲取源碼我是傳送門
主要邏輯都在proto和protoCusEnumCompiler兩個(gè)模塊里面
protoCusEnumCompiler負(fù)責(zé)生成修改pb生成類的jar邏輯
proto 則是存放pb文件和生成pb文件

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容