全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

Android上使用grpc的方法教程

前言

最近的一个项目使用到了grpc实现跨平台的远程调用,在安卓端使用的时候遇到了一些坑,这里记录一下。

首先根据grpc android的官方Demo配置grpc依赖,测试它的hello world工程。

编译谷歌官方的helloworld工程

添加rotobuf-gradle-plugin插件

首先添加rotobuf-gradle-plugin插件,他是用来从proto文件自动生成java代码的:

//Project的build.gradle中添加rotobuf-gradle-plugin插件
buildscript {
 ...
 dependencies {
 ...
 classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.0"
 ...
 }
 ...
}
//App的build.gradle中添加下面配置
apply plugin: 'com.google.protobuf'

protobuf {
 protoc {
 artifact = 'com.google.protobuf:protoc:3.0.0'
 }
 plugins {
 javalite {
  artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
 }
 grpc {
  artifact = 'io.grpc:protoc-gen-grpc-java:1.0.0' // CURRENT_GRPC_VERSION
 }
 }
 generateProtoTasks {
 all().each { task ->
  task.plugins {
  javalite {}
  grpc {
   // Options added to --grpc_out
   option 'lite'
  }
  }
 }
 }
}

添加proto文件并自动生成java代码

在src/main/目录下创建一个proto目录,并将官方的helloworld.proto放到proto目录下

之后只需要rebuild一下就能看到build/generated/source/proto/目录下根据helloworld.proto生成了几个Java类


添加安卓端grpc的依赖

//App的build.gradle中添加下面配置
 dependencies {
 ...
 compile 'io.grpc:grpc-okhttp:1.1.2'
 compile 'io.grpc:grpc-protobuf-lite:1.1.2'
 compile 'io.grpc:grpc-stub:1.1.2'
 compile 'javax.annotation:javax.annotation-api:1.2'
 ...
}
configurations.all {
 resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
 }

我这个时候报了这个错误

Warning:Conflict with dependency ‘com.google.code.findbugs:jsr305'. Resolved versions for app (3.0.0) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

这是因为com.google.code.findbugs:jsr305的版本不一致导致的

可以在App的build.gradle的android标签中配置一下解决

android {
 ...
 configurations.all {
 resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
 }
 ...
}

编写demo代码

public class MainActivity extends AppCompatActivity {
 private static final String TAG = "GrpcDemo";

 private static final int PROT = 55055;
 private static final String NAME = "linjw";
 private static final String HOST = "localhost";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 startServer(PROT);
 startClient(HOST, PROT, NAME);
 }

 private void startServer(int port){
 try {
  Server server = ServerBuilder.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){
 new GrpcTask(host, port, name).execute();
 }

 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("hello "+ request.getName())
   .build();
 }
 }

 private class GrpcTask extends AsyncTask<Void, Void, String> {
 private String mHost;
 private String mName;
 private int mPort;
 private ManagedChannel mChannel;

 public GrpcTask(String host, int port, String name) {
  this.mHost = host;
  this.mName = name;
  this.mPort = port;
 }

 @Override
 protected void onPreExecute() {
 }

 @Override
 protected String doInBackground(Void... nothing) {
  try {
  mChannel = ManagedChannelBuilder.forAddress(mHost, mPort)
   .usePlaintext(true)
   .build();
  GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(mChannel);
  HelloRequest message = HelloRequest.newBuilder().setName(mName).build();
  HelloReply reply = stub.sayHello(message);
  return reply.getMessage();
  } catch (Exception e) {
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  e.printStackTrace(pw);
  pw.flush();
  return "Failed... : " + System.lineSeparator() + sw;
  }
 }

 @Override
 protected void onPostExecute(String result) {
  try {
  mChannel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
  Thread.currentThread().interrupt();
  }
  Log.d(TAG, result);
 }
 }
}

这段代码运行会崩溃:

Caused by: io.grpc.ManagedChannelProvider$ProviderNotFoundException: No functional server found. Try adding a dependency on the grpc-netty artifact

猜测google使用netty替代了okhttp,尝试换成grpc-netty的依赖:

dependencies {
 ...
 compile 'io.grpc:grpc-netty:1.1.2'
 compile 'io.grpc:grpc-protobuf-lite:1.1.2'
 compile 'io.grpc:grpc-stub:1.1.2'
 compile 'javax.annotation:javax.annotation-api:1.2'
 ...
}

这么编译会报错

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/INDEX.LIST

需要加上下面的配置解决

android {
 ...
 packagingOptions {
 pickFirst 'META-INF/INDEX.LIST'
 pickFirst 'META-INF/LICENSE'
 pickFirst 'META-INF/io.netty.versions.properties'
 }
 ...
}

当然,还需要加上INTERNET权限,要不然运行的时候还是会崩溃。

最终就能看的下面的打印,这样安卓grpc的helloworld就成功了。

03-03 00:04:20.000 6137-6137/linjw.com.grpcdemo D/GrpcDemo: hello linjw

使用com.google.protobuf.Any

Any可以携带任意类型的数据,用法相当于c语言的void指针。在项目中是很常用的,但是谷歌在javalite的版本不支持Any。

如果在proto文件中使用了Any的话生成java代码就会有报错,例如将helloworld的proto文件改成下面的样子:

// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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;

import "google/protobuf/any.proto";

// The greeting service definition.
service Greeter {
 // Sends a greeting
 rpc SayHello (google.protobuf.Any) 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;
}

报错如下

google/protobuf/any.proto: File not found.
helloworld.proto: Import “google/protobuf/any.proto” was not found or had errors.
helloworld.proto:44:17: “google.protobuf.Any” is not defined.

使用grpc-jave代替grpc-javalite

但是现在做的这个项目的linux端实现已经用了Any,要改的话需要耗费比较大的精力。幸好尝试了下,发现安卓上也能跑支持Any的grpc-java。

首先我们要使用grpc-protobuf依赖替换grpc-protobuf-lite依赖

dependencies {
 ...
 compile 'io.grpc:grpc-netty:1.1.2'
 compile 'io.grpc:grpc-protobuf:1.1.2'
 compile 'io.grpc:grpc-stub:1.1.2'
 compile 'javax.annotation:javax.annotation-api:1.2'
 ...
}

接着修改protobuf-gradle-plugin配置使得自动生成java的代码而不是javalite的代码

protobuf {
 protoc {
  artifact = 'com.google.protobuf:protoc:3.0.0'
 }
 plugins {
  grpc {
   artifact = 'io.grpc:protoc-gen-grpc-java:1.0.0' // CURRENT_GRPC_VERSION
  }
 }
 generateProtoTasks {
  all().each { task ->
   task.builtins {
    java {}
   }
   task.plugins {
    grpc {}
   }
  }
 }
}

对应的修改helloworld的代码就能运行了

public class MainActivity extends AppCompatActivity {
 private static final String TAG = "GrpcDemo";

 private static final int PROT = 55055;
 private static final String NAME = "linjw";
 private static final String HOST = "localhost";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  startServer(PROT);
  startClient(HOST, PROT, NAME);
 }

 private void startServer(int port){
  try {
   Server server = ServerBuilder.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){
  new GrpcTask(host, port, name).execute();
 }

 private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
  public void sayHello(Any request, StreamObserver<HelloReply> responseObserver) {
   try {
    responseObserver.onNext(sayHello(request.unpack(HelloRequest.class)));
    responseObserver.onCompleted();
   } catch (InvalidProtocolBufferException e) {
    e.printStackTrace();
   }
  }

  private HelloReply sayHello(HelloRequest request) {
   return HelloReply.newBuilder()
     .setMessage("hello "+ request.getName())
     .build();
  }
 }

 private class GrpcTask extends AsyncTask<Void, Void, String> {
  private String mHost;
  private String mName;
  private int mPort;
  private ManagedChannel mChannel;

  public GrpcTask(String host, int port, String name) {
   this.mHost = host;
   this.mName = name;
   this.mPort = port;
  }

  @Override
  protected void onPreExecute() {
  }

  @Override
  protected String doInBackground(Void... nothing) {
   try {
    mChannel = ManagedChannelBuilder.forAddress(mHost, mPort)
      .usePlaintext(true)
      .build();
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(mChannel);
    HelloRequest message = HelloRequest.newBuilder().setName(mName).build();
    HelloReply reply = stub.sayHello(Any.pack(message));
    return reply.getMessage();
   } catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return "Failed... : " + System.lineSeparator() + sw;
   }
  }

  @Override
  protected void onPostExecute(String result) {
   try {
    mChannel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
   }
   Log.d(TAG, result);
  }
 }
}

完整的demo代码可以点这里在我的github中查看(也可以通过本地下载)

Android方法数不能超过65535的问题

最后使用grpc,方法数会超过65535,可以使用com.android.support:multidex去解决

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对的支持。


# android  # grpc  # 使用  # java  # Android使用GRPC进行通信过程解析  # Android搭建grpc环境过程分步详解  # 报错  # 自动生成  # 就能  # 目录下  # 几个  # 点这里  # 本地下载  # 他是  # 如有  # 也能  # 这段  # 可以通过  # 用了  # 并将  # 这个时候  # 还需要  # 不支持  # 只需要  # 可以使用  # 能看 


相关文章: ,有什么在线背英语单词效率比较高的网站?  如何通过二级域名建站提升品牌影响力?  交易网站制作流程,我想开通一个网站,注册一个交易网址,需要那些手续?  行程制作网站有哪些,第三方机票电子行程单怎么开?  天河区网站制作公司,广州天河区如何办理身份证?需要什么资料有预约的网站吗?  如何在腾讯云服务器快速搭建个人网站?  宝塔建站教程:一键部署配置流程与SEO优化实战指南  网站规划与制作是什么,电子商务网站系统规划的内容及步骤是什么?  Python文件管理规范_工程实践说明【指导】  建站主机与服务器功能差异如何区分?  如何用免费手机建站系统零基础打造专业网站?  大连 网站制作,大连天途有线官网?  平台云上自助建站如何快速打造专业网站?  网站制作软件免费下载安装,有哪些免费下载的软件网站?  清单制作人网站有哪些,近日“兴风作浪的姑奶奶”引起很多人的关注这是什么事情?  制作网站的公司有哪些,做一个公司网站要多少钱?  如何在Mac上搭建Golang开发环境_使用Homebrew安装和管理Go版本  建站之星代理商如何保障技术支持与售后服务?  广平建站公司哪家专业可靠?如何选择?  ,石家庄四十八中学官网?  建站之星如何保障用户数据免受黑客入侵?  宝塔建站助手安装配置与建站模板使用全流程解析  网站设计制作企业有哪些,抖音官网主页怎么设置?  定制建站策划方案_专业建站与网站建设方案一站式指南  详解一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)  ,购物网站怎么盈利呢?  成都网站制作报价公司,成都工业用气开户费用?  小型网站制作HTML,*游戏网站怎么搭建?  如何通过万网虚拟主机快速搭建网站?  在线制作视频的网站有哪些,电脑如何制作视频短片?  如何在阿里云高效完成企业建站全流程?  零基础网站服务器架设实战:轻量应用与域名解析配置指南  建站之星代理平台如何选择最佳方案?  如何快速辨别茅台真假?关键步骤解析  制作网站外包平台,自动化接单网站有哪些?  建站之星会员如何解锁更多建站功能?  c++怎么实现高并发下的无锁队列_c++ std::atomic原子变量与CAS操作【详解】  家庭服务器如何搭建个人网站?  建站之星安装步骤有哪些常见问题?  如何在阿里云ECS服务器部署织梦CMS网站?  北京网站制作的公司有哪些,北京白云观官方网站?  如何在Ubuntu系统下快速搭建WordPress个人网站?  如何快速查询域名建站关键信息?  C++ static_cast和dynamic_cast区别_C++静态转换与动态类型安全转换  Python lxml的etree和ElementTree有什么区别  建站之星图片链接生成指南:自助建站与智能设计教程  国美网站制作流程,国美电器蒸汽鍋怎么用官方网站?  如何在万网主机上快速搭建网站?  大连网站设计制作招聘信息,大连投诉网站有哪些?  手机怎么制作网站教程步骤,手机怎么做自己的网页链接? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。