如何在Kotlin中启用gRPC-Gateway及解决编译报错
解决gRPC-Kotlin+Bazel环境下gRPC-Gateway编译错误的方案
核心问题分析
手动复制google/api/annotations.proto和http.proto到本地目录是错误操作——Bazel依赖通过依赖声明而非文件复制管理,手动复制会打断原有依赖链,导致http.proto找不到google/protobuf/descriptor.proto这类底层依赖。正确做法是通过Bazel的WORKSPACE和BUILD配置引入官方依赖。
具体修复步骤
1. 更新WORKSPACE文件,引入必要依赖
在项目根目录的WORKSPACE中添加以下内容,引入googleapis(包含annotations.proto)和gRPC-Gateway的Bazel依赖:
# 引入googleapis,提供google/api/annotations.proto等文件 http_archive( name = "com_google_googleapis", sha256 = "d5a8306b438d7a26e0b79b291c7d4596e1a49f21c8b92d7d51d1f648d0e5b4a0", strip_prefix = "googleapis-0a95cd4d0b4d51a45f647e90f6d80401e6b7398d", urls = ["https://github.com/googleapis/googleapis/archive/0a95cd4d0b4d51a45f647e90f6d80401e6b7398d.zip"], ) # 引入gRPC-Gateway http_archive( name = "com_github_grpc_grpc_gateway", sha256 = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2", strip_prefix = "grpc-gateway-2.19.0", urls = ["https://github.com/grpc-ecosystem/grpc-gateway/archive/refs/tags/v2.19.0.zip"], ) # 加载gRPC-Gateway的依赖规则 load("@com_github_grpc_grpc_gateway//:repositories.bzl", "grpc_gateway_repositories") grpc_gateway_repositories() # 加载googleapis的依赖规则 load("@com_google_googleapis//:repository_rules.bzl", "googleapis_dependencies") googleapis_dependencies()
注:sha256和版本号可根据最新版调整,确保下载的依赖包校验通过
2. 修改BUILD.bazel文件,配置proto依赖
找到hello_world示例的BUILD.bazel文件(通常在examples/helloworld/src/main/proto/目录下),更新proto_library的依赖,并添加gRPC-Gateway的代码生成规则:
proto_library( name = "hello_world_proto", srcs = ["hello_world.proto"], deps = [ "@com_google_googleapis//google/api:annotations_proto", "@com_google_protobuf//:descriptor_proto", ], ) # 添加gRPC-Gateway的代码生成(生成HTTP网关相关代码) grpc_gateway_proto_library( name = "hello_world_gateway_proto", srcs = ["hello_world.proto"], deps = [":hello_world_proto"], ) # 如果需要生成Kotlin代码,确保原有grpc_kotlin_proto_library依赖正确 grpc_kotlin_proto_library( name = "hello_world_kt_proto", deps = [":hello_world_proto"], )
3. 清理手动复制的文件
删除之前手动复制到本地google/api/目录下的所有proto文件,避免Bazel解析路径冲突。
4. 重新构建项目
在项目根目录执行Bazel构建命令:
bazel build //examples/helloworld/...
关键说明
google/api/annotations.proto的依赖由@com_google_googleapis//google/api:annotations_proto提供,Bazel会自动拉取并管理相关文件,无需手动复制。http.proto是gRPC-Gateway的依赖,会通过grpc_gateway_repositories()自动引入,无需手动处理。
内容的提问来源于stack exchange,提问作者nsinnyc
相关产品推荐
相关产品推荐

