Springboot-grpc-Demo

grpc:一般使用的是 restful API,grpc和他有一样的机制,都是客户端和服务端进行通信,底层也都是 http传输协议,
grpc优势(场景)
1、通过 protobuf来定义接口,有更严格的接口约束,
2、通过 protobuf可以将数据 序列化为 二进制编码,减少传输量,提高性能。

因为现在一般都是分布式系统mgroc没有提供分布式系统的相关组件,所以grpc只是作为一个部件使用。

为了展示gRPC的工作原理,我们来构建一个客户端和相应的服务器,以公开一个简单的Hello World gRPC服务。

pom文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.7</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.espringboot</groupId>
	<artifactId>grpc_demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>grpc_demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<os-maven-plugin.version>1.6.1</os-maven-plugin.version>
		<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>net.devh</groupId>
			<artifactId>grpc-spring-boot-starter</artifactId>
			<version>2.4.0.RELEASE</version>
		</dependency>

	</dependencies>

	<build>
		<extensions>
			<extension>
				<groupId>kr.motd.maven</groupId>
				<artifactId>os-maven-plugin</artifactId>
				<version>${os-maven-plugin.version}</version>
			</extension>
		</extensions>

		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
			<!--grpc proto文件编译插件-->
			<plugin>
				<groupId>org.xolstice.maven.plugins</groupId>
				<artifactId>protobuf-maven-plugin</artifactId>
				<version>${protobuf-maven-plugin.version}</version>
				<configuration>
					<protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
					<pluginId>grpc-java</pluginId>
					<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier}</pluginArtifact>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>compile</goal>
							<goal>compile-custom</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>

	</build>

</project>

目录格式
在这里插入图片描述
注意:一定要把 proto文件夹 设置 资源文件,否则后续会报错

yaml文件

server:
  port: 8080
grpc:
  server:
    in-process-name: grpc
    # 修改服务端默认入参最大大小,默认值为4M ,这里修改为20M   20*1024*1024
    max-inbound-message-size: 20971520
    # grpc 端口号
    port: 8989
  client:
    GLOBAL:
      negotiation-type: plaintext
      # 修改客户端端默认入参最大大小,默认值为4M ,这里修改为20M   20*1024*1024
      max-inbound-message-size: 20971520
      # 客户端指定连接服务端地址
      address: 'static://127.0.0.1:8989'

编写 proto文件

syntax = "proto3";

package net.devh.boot.grpc.example;

option java_multiple_files = true;
option java_package = "net.devh.boot.grpc.examples.lib";
option java_outer_classname = "HelloWorldProto";

// 定义 sayHello 服务
service MyService {
  // 发送 一个 sayHello
  rpc SayHello (HelloRequest) returns (HelloReply) {
  }
}

// 请求体
message HelloRequest {
  string name = 1;
}

// 响应
message HelloReply {
  string message = 1;
}

Maven编译
在这里插入图片描述

这个时候 maven会把 proto文件编译生成java文件
在这里插入图片描述

编写 服务端

import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.examples.lib.HelloReply;
import net.devh.boot.grpc.examples.lib.HelloRequest;
import net.devh.boot.grpc.examples.lib.MyServiceGrpc;
import net.devh.boot.grpc.server.service.GrpcService;


@GrpcService
public class MyServiceImpl extends MyServiceGrpc.MyServiceImplBase{
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
        HelloReply reply = HelloReply.newBuilder()
                .setMessage("Hello ==> " + request.getName())
                .build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


}

编写客户端

@Component
public class GrpcClientExample {

    /**
     * 这里的名称为 proto 文件中 service 对应的名称,注意首字母小写
     */
    @GrpcClient("myService")
    private MyServiceGrpc.MyServiceBlockingStub myServiceStub;

    public String receiveGreeting(String name) {
        HelloRequest request = HelloRequest.newBuilder()
                .setName(name)
                .build();
        return myServiceStub.sayHello(request).getMessage();
    }

}

编写 controller

@RequestMapping("/api/v1/grpc")
@RestController
public class GrpcController {

    private final GrpcClientExample grpcClientExample;

    public GrpcController(GrpcClientExample grpcClientExample) {
        this.grpcClientExample = grpcClientExample;
    }

    @GetMapping("/get/{name}")
    public Object grpc(@PathVariable("name") String name) {
        String names = grpcClientExample.receiveGreeting(name);
        System.out.println("response.getMessage() = " + names);
        return names;
    }

}

运行项目 测试 --controller - > 客户端 ->服务端
在这里插入图片描述

参考:
https://people.blog.youkuaiyun.com/article/details/121575516

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值