Grpc微服务从零入门

快速入门

安装

JDK

毫无疑问,要想玩Java,就必须得先装Java JDK,目前公司主要使用的是Oracle JDK 8,安装完成后要配置环境才能正常使用,真蠢,不过也就那么一下下,认了吧。配置方法参考:
http://www.runoob.com/java/java-environment-setup.html

IDE

个人认为Java最好用的IDE就是IntelliJ IDEA (后面会简称IDEA)。IDEA最大的优势就是可定制能力很高。同时有着各种各样的插件能提供不少的扩展和便利。但是个人是希望统一使用默认的配置,不然在代码审查和指导的时候,各种快捷键按了没反应,会很尴尬。默认配置也是经过考验的,基本不会有多少反人类的快捷键,习惯就好。

常用插件

  • PlantUML 使用代码绘画UML图
  • Python 编写Python
  • Markdown 编写Markdown文档
  • google protocol 微服务Grpc框架
  • Lombok 扩展Java的语法特性

配置(Ctrl+Shift+A)

  • Show Line Number
  • TODO: 导入Formatter文件

Maven

目前使用Maven作为内部的依赖包管理工具,在使用之前需要配置内部的Maven私库,否则会默认连到外部的公有Maven仓库上。

Hello Java

个人认为TDD是个特别好的实践。所以从Hello Test开始吧。那么先了解一下Java的单元测试所用到的一些技术。

  • 测试用到的技术
    • JUnit 4:通用测试框架。官网
    • Mockito:在自动化单元测试中创建测试对象,为TDD或BDD提供支持。
    • PowerMock: 支持模拟静态方法、构造函数、final类和方法、私有方法以及移除静态初始化器的模拟工具。官网
    • AssertJ:支持流式断言提高测试的可读性。

Hallo Test

新建一个Maven项目,下一步,然后随便起个命名空间com.xudashu,再随便起个名hallo-test,然后随便起个方案名hallo-test,完成。
目录结构非常的清晰:
HalloTest
main里面是代码文件,
test里面是测试文件,
pom.xml是maven的依赖管理配置文件

首先在test的java里面编写SomeThingTest。
断言:assertThat(someThing.Do()).isEqualTo("Hallo Test");
然后alt+enter生成java源码,在生成的SomeThing.Do里面return "Hallo Test";运行测试 mvn clean test。查看hallo-test源码

Hallo Grpc

目前公司使用的微服务的核心技术主要是使用Google开源的GRPC,GRPC使用的是google protocol,(注:在编写这篇文档时,刷了一下git log,最新的GRPC(1.0.0-pre2)加入了thrift的支持。)

使用GRPC,当然要先引入GRPC的依赖包

GRPC的依赖包pom配置

    <properties>
        <grpc.version>1.0.0-pre2</grpc.version><!-- CURRENT_GRPC_VERSION -->
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/io.grpc/grpc-all -->
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-all</artifactId>
            <version>${grpc.version}</version>
        </dependency>

    </dependencies>

所有跨语言的RPC框架,几乎都会使用IDL接口描述语言,GRPC也不例外,GRPC的IDL接口描述语言语法大量参考了C++语法,所以相当简单易懂。

那么在使用之前,需要通过 protocol
buffer 的编译器 protoc 以及一个特殊的 Maven插件将IDL转化成Java语言才能正常的使用。

Maven插件的pom配置

   <build>
       <extensions>
           <extension>
               <groupId>kr.motd.maven</groupId>
               <artifactId>os-maven-plugin</artifactId>
               <version>1.4.1.Final</version>
           </extension>
       </extensions>
       <plugins>
           <plugin>
               <groupId>org.xolstice.maven.plugins</groupId>
               <artifactId>protobuf-maven-plugin</artifactId>
               <version>0.5.0</version>
               <configuration>
                   <!--
                     The version of protoc must match protobuf-java. If you don't depend on
                     protobuf-java directly, you will be transitively depending on the
                     protobuf-java version that grpc depends on.
                   -->
                   <protocArtifact>com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}</protocArtifact>
                   <pluginId>grpc-java</pluginId>
                   <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
               </configuration>
               <executions>
                   <execution>
                       <goals>
                           <goal>compile</goal>
                           <goal>compile-custom</goal>
                       </goals>
                   </execution>
               </executions>
           </plugin>
       </plugins>
   </build>

配置好环境就可以开工了,首先定义好接口契约。

IDL契约

syntax = "proto3";

option java_multiple_files = true;
option java_outer_classname = "HelloWorldProto";

package com.xudashu.helloworld;

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

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

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

然后mvn clean install生成代码,在Service层新建GreeterImpl类,继承GreeterGrpc.GreeterImplBase

public class GreeterImpl extends GreeterGrpc.GreeterImplBase {
    @Override
    public void sayHello(SayHelloRequest request, StreamObserver<SayHelloResponse> responseObserver) {
        SayHelloResponse response = SayHelloResponse.newBuilder()
                .setMessage("Hallo " +  request.getName()).build();

        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}

在Test里面,新建Application,使用NettyServer来启动Grpc服务。

public static void main(String[] args) throws Exception {
    int port = 8080;
    NettyServerBuilder.forPort(port)
            .addService(ServerInterceptors.intercept(new GreeterImpl()))
            .build().start();
}

启动服务后,使用NettyChannel来创建Grpc的通道,创建完成后,和调用本地应用一样简单方便了。

      channel = NettyChannelBuilder.forAddress("127.0.0.1", port)
              .negotiationType(NegotiationType.PLAINTEXT)
              .build();

      blockingStub = GreeterGrpc.newBlockingStub(channel);

      SayHelloRequest request = SayHelloRequest.newBuilder()
               .setName("许大叔")
               .build();

       SayHelloResponse response = blockingStub.sayHello(request);

       assertThat(response.getMessage()).isEqualTo("Hallo 许大叔");

查看hallo-grpc源码

posted on 2016-08-14 22:42  艾晨爸  阅读(1673)  评论(0编辑  收藏  举报

导航