Android使用gRPC(一)

首先需要配置Android studio对protobuf的支持

参考资料

https://blog.csdn.net/Dream_go888/article/details/80092991
https://plugins.gradle.org/plugin/com.google.protobuf#new-plugin-mechanism-info-body

https://github.com/google/protobuf-gradle-plugin

第一步,添加protobuf-gradle-plugin插件

参考https://github.com/google/protobuf-gradle-plugin,在项目根目录build.gradle里添加

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5'
  }
}

完整示例如下

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
        //yuyong-->https://github.com/google/protobuf-gradle-plugin
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        // yuyong-->https://github.com/google/protobuf-gradle-plugin
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

同步项目

第二步,对app模块进行配置,使之支持protobuf

在app模块下build.gradle里添加:

插件配置

apply plugin: 'com.google.protobuf'

指明proto文件位置

    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
            }
        }
    }

定义protoc编译(实际上就是根据proto生成java或者C++代码文件)规则

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.5.1-1'
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
                // Add cpp output without any option.
                // DO NOT omit the braces if you want this builtin to be added.
                cpp {}
            }
        }
    }
    generatedFilesBaseDir = "$projectDir/src/generated"
}

添加相关Java库支持(如果需要支持C++,需要添加C++库的支持)

    implementation 'com.google.protobuf:protobuf-java:3.5.1'
    implementation 'com.google.protobuf:protoc:3.5.1-1'

完整示例如下

apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.thinking.client"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
            }
        }
    }
}
protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.5.1-1'
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
                // Add cpp output without any option.
                // DO NOT omit the braces if you want this builtin to be added.
                cpp {}
            }
        }
    }
    generatedFilesBaseDir = "$projectDir/src/generated"
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.google.protobuf:protobuf-java:3.5.1'
    implementation 'com.google.protobuf:protoc:3.5.1-1'
}

同步,rebuild

至此,Android Studio完整了对protobuf的支持。

下面参考https://grpc.io/docs/quickstart/android.html创建一个test.proto文件

// Copyright 2015, gRPC Authors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.thinking.client";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

rebuild

可以看到在$projectDir/src/generated下可以看到由test.proto文件生成的Java和C++代码文件。




Android使用 gRPC,您需要进行以下步骤: 1. 在您的 Android 项目中添加 gRPC 和 protobuf 的依赖项。您可以在项目的 build.gradle 文件中添加以下代码: ``` implementation 'io.grpc:grpc-okhttp:1.40.1' implementation 'io.grpc:grpc-protobuf-lite:1.40.1' implementation 'io.grpc:grpc-stub:1.40.1' implementation 'com.google.protobuf:protobuf-java:3.18.0' ``` 2. 定义您的 gRPC 服务和消息类型的.proto 文件。您可以使用 Protocol Buffers 语言来定义它们。例如,创建一个名为 "example.proto" 的文件,并在其中定义服务和消息类型。 示例 "example.proto" 文件内容: ```protobuf syntax = "proto3"; package com.example.grpc; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) {} } message ExampleRequest { string message = 1; } message ExampleResponse { string reply = 1; } ``` 3. 在您的项目中运行 Protocol Buffers 编译器,以生成 Java 类。您可以使用 `protoc` 命令行工具或 Gradle 插件来完成此操作。例如,使用 Gradle 插件可以在项目的 build.gradle 文件中添加以下代码: ``` protobuf { protoc { artifact = 'com.google.protobuf:protoc:3.18.0' } plugins { grpc { artifact = 'io.grpc:protoc-gen-grpc-java:1.40.1' } } generateProtoTasks { all()*.plugins { grpc {} } } } ``` 然后,在命令行中运行 `./gradlew generateProto` 命令,以生成 Java 类。 4. 创建 gRPC 客户端代码。您可以使用生成的 Java 类来创建客户端代码,并与 gRPC 服务进行通信。在您的 Android 项目中,您可以创建一个 gRPC 客户端类,以处理与服务器的通信。 示例 gRPC 客户端类: ```java import com.example.grpc.ExampleRequest; import com.example.grpc.ExampleResponse; import com.example.grpc.ExampleServiceGrpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; public class GrpcClient { private final ManagedChannel channel; private final ExampleServiceGrpc.ExampleServiceStub stub; public GrpcClient(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port) .usePlaintext() .build(); stub = ExampleServiceGrpc.newStub(channel); } public void callExampleMethod(String message, StreamObserver<ExampleResponse> responseObserver) { ExampleRequest request = ExampleRequest.newBuilder() .setMessage(message) .build(); stub.exampleMethod(request, responseObserver); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } } ``` 这是一个简单的示例,演示了如何创建 gRPC 客户端并调用服务的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值