优雅解决:M1 芯片maven 编译protobuf生成Java代码时,不能找到protoc-gen-grpc-java:exe:osx-aarch_64

在Java项目中,使用Maven在编译gRPC的protobuf文件时,需要使用protobuf-maven-plugin进行java文件生成,Maven的pom.xml文件中配置如下:

<build>
    <extensions>
      <extension>
        <!-- Required for protobuf-maven-plugin since Google provides platform-specific
             protoc executables -->
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.6.2</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.6.1</version>
        <configuration>
          <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}
          </protocArtifact>
          <pluginId>grpc-java</pluginId>
          <pluginArtifact>
            io.grpc:protoc-gen-grpc-java:1.29.0:exe:${os.detected.classifier}
          </pluginArtifact>
          <protoSourceRoot>${basedir}/../proto</protoSourceRoot>
          <clearOutputDirectory>false</clearOutputDirectory>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>compile-custom</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
</build>

其中

${os.detected.classifier}

是在编译时自动获取系统的类型和cpu类型,报错就是出现在这里,因为protoc-gen-grpc-java没有aarch64(Apple Silicon的cpu架构)的版本,因此需要在编译时,将其替换为x86_64。

在maven的pom文件中可以指定profile,通过profile设置编译时使用的参数值,因此需要在pom文件中,build标签前添加:

<profiles>
    <profile>
      <id>apple-silicon</id>
      <activation>
        <os>
          <arch>aarch64</arch> <!-- when running on Apple Silicon, will trigger the profile -->
        </os>
      </activation>
      <properties>
        <os.detected.classifier>osx-x86_64</os.detected.classifier> <!-- use the x86_64 version of protoc -->
      </properties>
    </profile>
  </profiles>

其中,activation标签是设置在什么条件下使用当前profile。这里我们将触发条件设置为os的cpu的架构为aarch64时触发,触发后将设置properties,将property “os.detected.classifier”设置为osx-x86_64,这样在编译时,获取到的 ${os.detected.classifier}的值将被替换成osx-x86_64。而在os的cpu不匹配时,将从系统中获取当前编译机器的cpu架构。

Maven的xsd约束文件可参考:Maven Model - Maven 其中包括3.0和4.0的xsd文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值