Grpc demo java 实现

环境

JDK8 + Maven3.6.3
我的 Grpc-java demo https://github.com/999bug/grpc-java 记得star😊😊

搭建步骤

1、利用代码编译器创建maven 项目

2、添加依赖坐标

 <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.44.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.44.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.44.0</version>
        </dependency>
        <dependency> <!-- necessary for Java 9+ -->
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

3、添加构建grpc proto插件

<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.19.2:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.44.0:exe:${os.detected.classifier}</pluginArtifact>
                    <protoSourceRoot>src/main/proto</protoSourceRoot>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

注意
<protoSourceRoot>src/main/proto</protoSourceRoot>
protoSourceRoot 设置proto文件的位置,不然插件不能正常编译
在这里插入图片描述

4、在protoSourceRoot 设置的文件夹下面创建helloWord.proto 文件,后缀必须为.proto,文件名无所谓

syntax = "proto3";

option java_multiple_files = true;
//指定该proto文件编译成的java源文件的包名
option java_package = "com.ncst.grpc.protobuf";
// 表示下面的message编译成的java类文件的名字
option java_outer_classname = "GrpcHelloProto";

package Hello;
// 使用的时候此类是所有使用类的前缀,定义rpc方法
如HelloGrpc、HelloBlockingStub、HelloResponse、HelloRequest
service Hello {
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

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

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

5、利用 Maven 插件,构建grpc 源代码

  • 首先运行compile
  • 然后接着运行compile-custom
    在这里插入图片描述

6、构建完成会发现在 target 包中生成如下代码

在这里插入图片描述

7、将protobuf 包移入项目中

在这里插入图片描述

编写server 端代码

1、远程调用方法实现类 HelloServiceImpl

package client.service;

import client.grpc.HelloGrpc;
import client.grpc.protobuf.HelloRequest;
import client.grpc.protobuf.HelloResponse;
import io.grpc.stub.StreamObserver;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class HelloServiceImpl extends HelloGrpc.HelloImplBase {

    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        HelloResponse helloResponse = HelloResponse.newBuilder()
                .setMessage("我是业主晓丹,我不喜欢保安,我希望每天都说 宝 早安,而不是早 保安!")
                .build();
        responseObserver.onNext(helloResponse);
        responseObserver.onCompleted();
        System.out.println("message from Grpc-client:" + request.getName());
    }
}

2、ServerService

package client.service;

import io.grpc.ServerBuilder;
import java.io.IOException;

/**
 * @author Lsy
 * @date 2022/2/21
 */
public class ServerService {
    private static final int port = 10086;
    private static io.grpc.Server server;

    public static void start() throws IOException, InterruptedException {
        server = ServerBuilder.forPort(port)
                .addService(new HelloServiceImpl())
                // 设置服务器上允许接收的最大邮件大小。如果未调用,则默认为4 MiB,所以要设置此参数
                .maxInboundMessageSize(Integer.MAX_VALUE)
                .build()

                .start();
        System.out.println("server start port: " + port);
        server.awaitTermination();
    }

}

3、Server 端启动类

package client.stater;

import client.service.ServerService;

import java.io.IOException;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerService.start();
    }
}

Client 端

1、BaseService

package client.service;

import client.grpc.HelloGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public abstract class BaseService {

    protected final ManagedChannel channel;
    protected final HelloGrpc.HelloBlockingStub blockingStub;

    public BaseService(String host, int port) {
        channel = ManagedChannelBuilder
                .forAddress(host, port)
                .usePlaintext()
                // 传输的数据大于4MB时,需要指定此参数
                .maxInboundMessageSize(Integer.MAX_VALUE)
                .build();
        blockingStub = HelloGrpc.newBlockingStub(channel);
    }

    public void shutdown() {
        try {
            channel.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public abstract void sayHello(String str);
}

2、BaseServiceImpl

package client.service;

import client.grpc.protobuf.HelloRequest;
import client.grpc.protobuf.HelloResponse;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class BaseServiceImpl extends BaseService {

    public BaseServiceImpl(String host, int port) {
        super(host, port);
    }

    @Override
    public void sayHello(String str) {
        HelloRequest request = HelloRequest.newBuilder()
                .setName(str)
                .build();
        HelloResponse response;
        response = blockingStub.sayHello(request);
        System.out.println("message from Grpc-server: " + response.getMessage());
        System.out.println();
    }

}

3、Client 启动类

package client.stater;

import client.service.BaseService;
import client.service.BaseServiceImpl;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class Client {
    public static void main(String[] args) {
        BaseService client = new BaseServiceImpl("127.0.0.1", 10086);
        client.sayHello("我是一名保安,保卫一方平安,爱吃小熊饼干,喜欢业主晓丹");
        client.shutdown();
    }
}

调用结果

Server 端

在这里插入图片描述

Client 端

在这里插入图片描述

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 Android gRPC Java 传输文件的演示,其中包括客户端和服务器端的代码。 1. 客户端代码 ```java public class FileTransferClient { private ManagedChannel channel; private FileTransferServiceGrpc.FileTransferServiceBlockingStub blockingStub; public FileTransferClient(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port) .usePlaintext() .build(); blockingStub = FileTransferServiceGrpc.newBlockingStub(channel); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public void uploadFile(File file) { try { FileInputStream inputStream = new FileInputStream(file); StreamObserver<FileChunk> responseObserver = blockingStub.uploadFile(new StreamObserver<UploadStatus>() { @Override public void onNext(UploadStatus value) { Log.d("FileUpload", "Upload status: " + value.getStatus()); } @Override public void onError(Throwable t) { Log.e("FileUpload", "Upload error: " + t.getMessage()); } @Override public void onCompleted() { Log.d("FileUpload", "Upload completed"); } }); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { FileChunk fileChunk = FileChunk.newBuilder() .setData(ByteString.copyFrom(buffer, 0, bytesRead)) .build(); responseObserver.onNext(fileChunk); } responseObserver.onCompleted(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 服务器端代码 ```java public class FileTransferServer { private static final Logger logger = Logger.getLogger(FileTransferServer.class.getName()); private Server server; public void start(int port) throws IOException { server = ServerBuilder.forPort(port) .addService(new FileTransferServiceImpl()) .build() .start(); logger.info("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.err.println("*** Shutting down gRPC server since JVM is shutting down"); FileTransferServer.this.stop(); System.err.println("*** Server shut down"); } }); } private void stop() { if (server != null) { server.shutdown(); } } private void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination(); } } public static void main(String[] args) throws IOException, InterruptedException { final FileTransferServer server = new FileTransferServer(); server.start(50051); server.blockUntilShutdown(); } static class FileTransferServiceImpl extends FileTransferServiceGrpc.FileTransferServiceImplBase { private FileOutputStream outputStream; @Override public StreamObserver<FileChunk> uploadFile(StreamObserver<UploadStatus> responseObserver) { outputStream = null; try { outputStream = new FileOutputStream("path_to_save_file"); // 修改为你想要保存文件的路径 } catch (FileNotFoundException e) { e.printStackTrace(); } return new StreamObserver<FileChunk>() { @Override public void onNext(FileChunk value) { try { outputStream.write(value.getData().toByteArray()); } catch (IOException e) { e.printStackTrace(); } } @Override public void onError(Throwable t) { t.printStackTrace(); } @Override public void onCompleted() { try { outputStream.flush(); outputStream.close(); UploadStatus uploadStatus = UploadStatus.newBuilder() .setStatus("Success") .build(); responseObserver.onNext(uploadStatus); responseObserver.onCompleted(); } catch (IOException e) { e.printStackTrace(); } } }; } } } ``` 这个示例演示了如何使用 gRPC 在 Android 上上传文件。在客户端代码中,我们创建了一个 `FileTransferClient` 类,它包含了与服务器通信的代码。在服务器端代码中,我们创建了一个 `FileTransferServer` 类,它包含了接收上传文件的代码。文件被分成块,并逐个发送到服务器。在服务器端,每个块被写入文件,直到接收到所有的块。在客户端,我们会收到上传的状态,包括上传是否成功以及错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值