RPC概念
RPC(Remote Procedure Call)远程过程调用, 是一个请求-响应协议。RPC 由客户机发起,客户机向已知的远程服务器发送请求消息,以使用提供的参数执行指定的过程。远程服务器向客户端发送响应,应用程序继续其进程。当服务器处理调用时,客户机被阻塞(它会等到服务器完成处理之后再继续执行) ,除非客户机向服务器发送异步请求,比如 XMLHttpRequest。在各种实现中存在许多变体和微妙之处,导致了各种不同的(不兼容的) RPC 协议。
RPC 框架原理
RPC 架构主要包括三部分:
- 服务注册中心(Registry),负责将本地服务发布成远程服务,管理远程服务,提供给服务消费者使用。
- 服务提供者(Server),提供服务接口定义与服务实现类。
- 服务消费者(Client),通过远程代理对象调用远程服务。
RPC 调用过程
- 客户端(client)以本地调用方式调用服务;
- 客户端存根(client stub)接收到调用后,负责将方法、参数等组装成能够进行网络传输的消息体(将消息体对象序列化为二进制);
- 客户端通过 sockets 将消息发送到服务端;
- 服务端存根(server stub)收到消息后进行解码(将消息对象反序列化);
- 服务端存根(server stub)根据解码结果调用本地的服务;
- 本地服务执行并将结果返回给服务端存根(server stub);
- 服务端存根(server stub)将返回结果打包成消息(将结果消息对象序列化);
- 服务端(server)通过 sockets 将消息发送到客户端;
- 客户端存根(client stub)接收到结果消息,并进行解码(将结果消息发序列化);
- 客户端(client)得到最终结果
HTTP 和 RPC 的优缺点
HTTP | RPC | |
---|---|---|
传输协议 | 基于HTTP协议 | 可以基于TCP协议,也可以基于HTTP协议 |
传输效率 | 如果是基于HTTP1.1的协议,请求中会包含很多无用的内容,如果是基于HTTP2.0,那么简单的封装以下是可以作为一个RPC来使用的,这时标准RPC框架更多的是服务治理 | 使用自定义的TCP协议,可以让请求报文体积更小,或者使用HTTP2协议,也可以很好的减少报文的体积,提高传输效率 |
性能消耗 | 大部分是通过json来实现的,字节大小和序列化耗时都比thrift要更消耗性能 | 可以基于thrift实现高效的二进制传输 |
负载均衡 | 需要配置Nginx,HAProxy来实现 | 基本都自带了负载均衡策略 |
服务治理 | 需要事先通知,修改Nginx/HAProxy配置 | 能做到自动通知,不影响上游 |
什么是GRPC
在 gRPC 中,客户机应用程序可以直接调用不同机器上服务器应用程序上的方法,就像它是一个本地对象一样,这使得创建分布式应用程序和服务更加容易。与许多 RPC 系统一样,gRPC 基于定义服务的思想,指定可以通过参数和返回类型远程调用的方法。在服务器端,服务器实现这个接口并运行一个 gRPC 服务器来处理客户端调用。在客户端,客户端有一个存根(在某些语言中称为客户端) ,它提供与服务器相同的方法。
GRPC-Java快速构建
1、首先创建一个maven项目
2、配置pom.xml文件
- 添加grpc的依赖
- 添加grpc插件,用于根据proto文件生成服务源代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>grpc</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>client</module>
<module>server</module>
</modules>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<os.detected.classifier>windows-x86_64</os.detected.classifier>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.24.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.24.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.24.0</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.9.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.24.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3、添加server子模块
① 、创建GreetingService.proto文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/18b1f12a325749e589f4573202063ac3.png
syntax = "proto3";
package com.example.grpc;
//指定生成的服务源码的文件名称,否则为GreetingServiceOuterClass
option java_outer_classname = "GreetingServiceClass";
//HelloRequest、HelloResponse和GreetingService文件分开,生成多个文件
option java_multiple_files = true;
// Request payload
message HelloRequest {
// Each message attribute is strongly typed.
// You also must assign a "tag" number.
// Each tag number is unique within the message.
string name = 1;
// This defines a strongly typed list of String
repeated string hobbies = 2;
// There are many more basics types, like Enum, Map
// See https://developers.google.com/protocol-buffers/docs/proto3
// for more information.
}
message HelloResponse {
string greeting = 1;
}
// Defining a Service, a Service can have multiple RPC operations
service GreetingService {
// Define a RPC operation
rpc greeting(HelloRequest) returns (HelloResponse);
}
②、生成服务的java源码
运行
mvn protobuf:compile
mvn protobuf:compile-custom
即可生成服务源码
![在这里插入图片描述](https://img-blog.csdnimg.cn/916c1c6bdd24412a8000be469dca33a7.png
如果生成的代码不能作为源码使用,可以对该包文件右击Mark Directory as -》Source Root
③、接下来创建grpc服务类GreetingServiceImpl
package com.example.grpc;
import io.grpc.stub.StreamObserver;
public class GreetingServiceImpl extends com.example.grpc.GreetingServiceGrpc.GreetingServiceImplBase {
@Override
public void greeting(com.example.grpc.HelloRequest request,
StreamObserver<com.example.grpc.HelloResponse> responseObserver) {
// HelloRequest has toString auto-generated.
System.out.println(request);
// You must use a builder to construct a new Protobuffer object
com.example.grpc.HelloResponse response = com.example.grpc.HelloResponse.newBuilder()
.setGreeting("Hello there, " + request.getName())
.build();
// Use responseObserver to send a single response back
responseObserver.onNext(response);
// When you are done, you must call onCompleted.
responseObserver.onCompleted();
}
}
④、创建server启动类App
package com.example.grpc;
import io.grpc.*;
public class App
{
public static void main( String[] args ) throws Exception
{
// Create a new server to listen on port 8080
Server server = ServerBuilder.forPort(8080)
.addService(new GreetingServiceImpl())
.build();
// Start the server
server.start();
// Server threads are running in the background.
System.out.println("Server started");
// Don't exit the main thread. Wait until server is terminated.
server.awaitTermination();
}
}
⑤、最后启动服务器
mvn -DskipTests package exec:java -Dexec.mainClass=com.example.grpc.App
4、添加client模块
①、配置pom.xml
引入server模块中生成的protobuf源码
②、创建消费用例
package com.example.grpc;
import io.grpc.*;
public class Client
{
public static void main( String[] args ) throws Exception
{
// Channel is the abstraction to connect to a service endpoint
// Let's use plaintext communication because we don't have certs
final ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8080")
.usePlaintext(true)
.build();
// It is up to the client to determine whether to block the call
// Here we create a blocking stub, but an async stub,
// or an async stub with Future are always possible.
com.example.grpc.GreetingServiceGrpc.GreetingServiceBlockingStub stub = com.example.grpc.GreetingServiceGrpc.newBlockingStub(channel);
com.example.grpc.HelloRequest request =
com.example.grpc.HelloRequest.newBuilder()
.setName("Ray")
.build();
// Finally, make the call using the stub
com.example.grpc.HelloResponse response =
stub.greeting(request);
System.out.println(response);
// A Channel should be shutdown before stopping the process.
channel.shutdownNow();
}
}
③、运行用例访问server
注意:工作中会直接对proto文件生成服务源码,然后为该服务创建一个指定的gav项目,然后在使用该服务的项目的pom中添加依赖即可,该工作一般由公司内部的自动化工具完成
参考文章
https://www.itzishu.com/archives/rpcdiffhttp.html
https://www.techtarget.com/searchapparchitecture/definition/Remote-Procedure-Call-RPC
gRPC官方文档
proto官方文档
https://codelabs.developers.google.com/codelabs/cloud-grpc-java#0