欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android搭建grpc環(huán)境過程分步詳解

 更新時間:2023年04月11日 10:11:41   作者:haohulala  
本篇文章使用的IDE是Android Studio。這里先吐槽一句,安卓項目搭建grpc環(huán)境,不管是引入插件還是引入第三方庫,對于版本的要求都極為苛刻,一旦版本不匹配就會報錯,所以對于版本的搭配一定要注意

下面介紹的這個版本搭配是我研究好久好久才跑通的,這在我的電腦上是一組可行的配置,如果你使用了同樣的配置跑不通,那可能是環(huán)境中某一部分還是有不同的地方,需要你自己再去找一下解決問題的辦法,那么話不多說,直接上配置吧。

各種配置文件

首先我們需要設置三個配置文件,如下圖所示

我們先來看一下項目設置setting.gradle,按照我的理解,這里應該是設置一些gradle倉庫地址,還有項目中包含的模塊等等信息。

我的配置是這樣寫的

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven { url 'https://repo.eclipse.org/content/repositories/paho-releases/'}
    }
}
rootProject.name = "grpc_project_plus"
include ':app'

接著是項目的的build.gradle,這里面需要引入一些插件和進行gradle版本設置,其中gradle版本設置也是一個坑,版本號要設置對才行

buildscript {
    repositories {
        maven{ url 'https://maven.aliyun.com/repository/jcenter'}
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
        maven { url 'https://maven.aliyun.com/repository/public' }
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.2.0"
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.17"
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

從上面的配置中我們可以看出,我們使用的gradle插件的版本是7.2.0,然后配置的gradle版本是7.4,具體的設置方法就是到gradle的配置文件中指定

當然也有一個簡單的辦法,就是到project structure中去指定

上面這張圖按照我的理解,上面是插件的版本號,下面就是gradle的版本號,這兩個不對應的話容易出問題,這里順便說一下,我的Android Studio的版本應該是2021.3.1,就是海豚的圖標。(經過這次的環(huán)境搭建,我現(xiàn)在對于版本號真的非常敏感,調版本號真的太折磨人了)

最后就是模塊的build.gradle,我找到的一個能跑通demo的設置如下

plugins {
    id 'com.android.application'
    id 'com.google.protobuf'
}
android {
    namespace 'com.example.grpc_project_plus'
    compileSdk 32
    defaultConfig {
        applicationId "com.example.grpc_project_plus"
        minSdk 29
        targetSdk 32
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
        exclude group: 'com.google.guava', module: 'listenablefuture'
    }
    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
            }
        }
    }
    packagingOptions {
        pickFirst 'META-INF/INDEX.LIST'
        pickFirst 'META-INF/LICENSE'
        pickFirst 'META-INF/io.netty.versions.properties'
    }
}
protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.17.2'
    }
    plugins {
        /*javalite {
            artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
        }*/
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.39.0' // CURRENT_GRPC_VERSION
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java { option 'lite' }
            }
            task.plugins {
                grpc { // Options added to --grpc_out
                    option 'lite' }
            }
        }
    }
}
dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    /*implementation 'io.grpc:grpc-okhttp:1.1.2'
    implementation 'io.grpc:grpc-netty:1.1.2'
    implementation 'io.grpc:grpc-protobuf-lite:1.1.2'
    implementation 'io.grpc:grpc-stub:1.1.2'
    implementation 'javax.annotation:javax.annotation-api:1.2'*/
    // You need to build grpc-java to obtain these libraries below.
    implementation 'io.grpc:grpc-netty:1.39.0'
    implementation 'io.grpc:grpc-okhttp:1.39.0' // CURRENT_GRPC_VERSION
    implementation 'io.grpc:grpc-protobuf-lite:1.39.0' // CURRENT_GRPC_VERSION
    implementation 'io.grpc:grpc-stub:1.39.0' // CURRENT_GRPC_VERSION
    implementation 'org.apache.tomcat:annotations-api:6.0.53'
}

編寫proto文件并編譯

配置好了上述環(huán)境后,我們需要編譯proto文件。

首先在main目錄下新建一個文件夾proto,然后編寫hello.proto文件。

文件的內容如下

syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
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;
}

這是一個簡單的grpc接口調用,具體的語法我就不說了,這篇文章主要是講環(huán)境搭建。

接著編譯項目,如果編譯成功的話,可以在build文件夾中看到grpc相關的java文件。

編寫簡單的demo代碼

這是最后一步,在主Activity中編寫簡單的客戶端和服務端代碼測試grpc服務是否可以正常使用。

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "GrpcDemo";
    private static final int PROT = 56322;
    private static final String NAME = "hello world";
    private static final String HOST = "localhost";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "start");
        startServer(PROT);
        Log.d(TAG, "start server.");
        startClient(HOST, PROT, NAME);
        Log.d(TAG, "start client.");
    }
    private void startServer(int port){
        try {
            NettyServerBuilder.forPort(port)
                    .addService(new GreeterImpl())
                    .build()
                    .start();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, e.getMessage());
        }
    }
    private void startClient(String host, int port, String name){
        ManagedChannel mChannel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build();
        GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(mChannel);
        HelloRequest message = HelloRequest.newBuilder().setName(name).build();
        stub.sayHello(message, new StreamObserver<HelloReply>() {
            @Override
            public void onNext(HelloReply value) {
                //Log.d(TAG, "sayHello onNext.");
                Log.d(TAG, value.getMessage());
            }
            @Override
            public void onError(Throwable t) {
                Log.d(TAG, "sayHello onError.");
            }
            @Override
            public void onCompleted() {
                Log.d(TAG, "sayHello onCompleted.");
            }
        });
    }
    private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            responseObserver.onNext(sayHello(request));
            responseObserver.onCompleted();
        }
        private HelloReply sayHello(HelloRequest request) {
            return HelloReply.newBuilder()
                    .setMessage(request.getName())
                    .build();
        }
    }
}

然后需要在AndroidManifest.xml文件中添加網(wǎng)絡權限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Grpc_project_plus"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>
</manifest>

運行上述代碼,如果能在控制臺看到下面的這句話就說明環(huán)境搭建成功了。

結語

這次的環(huán)境搭建真的非常艱難,前前后后遇到了各種問題。不得不說,安卓編程對于版本太敏感了,只要有一個版本沒有對應上項目都可能跑不通。

到此這篇關于Android搭建grpc環(huán)境過程分步詳解的文章就介紹到這了,更多相關Android搭建grpc環(huán)境內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論