grpc實現(xiàn)文件傳輸?shù)目蛻舳撕头?wù)端例子

grpc是一個跨語言的rpc框架谤专,通過protobuf定義接口和傳輸?shù)母袷绞迦瘢哂懈邏嚎s涕烧,高性能(基于http/2的多路復(fù)用和壓縮頭)等特性袁辈。這里簡單介紹一下怎樣實現(xiàn)一個傳輸文件的客戶端和服務(wù)端模型区赵,代碼簡單惭缰,沒怎么封裝,有興趣的同學(xué)可以基于這個自己進行改造笼才。

1.環(huán)境準備

  • 開發(fā)工具: idea
  • maven: 3.6.1
  • jdk8

2.protobuf插件安裝

image.png

1.2 maven配置


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <grpc.version>1.25.0</grpc.version>
    <protobuf.version>3.5.1</protobuf.version>
    <protoc.version>3.5.1-1</protoc.version>
    <netty.tcnative.version>2.0.7.Final</netty.tcnative.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>io.dropwizard.metrics</groupId>
      <artifactId>metrics-core</artifactId>
      <version>4.0.0</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty</artifactId>
      <version>${grpc.version}</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-protobuf</artifactId>
      <version>${grpc.version}</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-stub</artifactId>
      <version>${grpc.version}</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-alts</artifactId>
      <version>${grpc.version}</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-testing</artifactId>
      <version>${grpc.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-tcnative-boringssl-static</artifactId>
      <version>${netty.tcnative.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.api.grpc</groupId>
      <artifactId>proto-google-common-protos</artifactId>
      <version>1.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java-util</artifactId>
      <version>${protobuf.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.9.5</version>
      <scope>test</scope>
    </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.5.0.Final</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:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
          <pluginId>grpc-protocol-buffers</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>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

3.proto文件編寫

  • 在src/main目錄下建一個proto目錄漱受。
  • 在proto目錄下新建一個File.ptoto文件
syntax = "proto3";
package file;
option java_multiple_files = true;
option java_package = "com.demo.grpc.file";
option java_outer_classname = "File";

service FileService {
    rpc Upload (Request) returns (Response) {}
}

message Request{
    // 定義文件為字節(jié)類型
    bytes file = 1;
    string name = 2;
}

message Response{
    int32 code = 1;
    string msg = 2;
}

4編譯

  • 執(zhí)行插件的protobuf-compile 生成基礎(chǔ)代碼


    image.png
image.png
  • 執(zhí)行插件的protobuf-compile-custom 生成grpc類


    image.png

    image.png

5.編寫服務(wù)端代碼

import com.demo.grpc.file.FileServiceGrpc;
import com.demo.grpc.file.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import io.grpc.ServerBuilder;

/**
 * @Author: pengjunming
 * @Date:2020/1/7 22:03
 * @Description:
 */
public class Server {
    private io.grpc.Server server;
    private static final int PORT = 8888;


    public static void main(String[] args) throws IOException, InterruptedException {
        Server server = new Server();
        server.start(PORT);
        server.await();
    }

    private void start(int port) throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(new BasicCalImpl())
                .build()
                .start();
        // 添加鉤子,在程序關(guān)閉時自動關(guān)閉服務(wù)端
        addHook();
    }

    private void addHook() {
        Runtime.getRuntime()
                .addShutdownHook(
                        new Thread(
                                () -> {
                                    System.out.println("監(jiān)聽到JVM停止,正在關(guān)閉GRPC服務(wù)....");
                                    this.stop();
                                    System.out.println("服務(wù)已經(jīng)停止...");
                                }));
    }

    /**
     * 關(guān)閉服務(wù)
     */
    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void await() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    static class BasicCalImpl extends FileServiceGrpc.FileServiceImplBase {

        @Override
        public void upload(com.demo.grpc.file.Request request,
                           io.grpc.stub.StreamObserver<com.demo.grpc.file.Response> responseObserver) {
            byte[] bytes = request.getFile().toByteArray();
            System.out.println(String.format("收到文件%s長度%s", request.getName(), bytes.length));
            File f = new File("D:/tmp/" + request.getName());
            Response response;
            if (f.exists()) {
                f.delete();
            }
            try (OutputStream os = new FileOutputStream(f)) {
                os.write(bytes);
                response = Response.newBuilder().setCode(1).setMsg("上傳成功").build();
            } catch (IOException e) {
                response = Response.newBuilder().setCode(-1).setMsg(String.format("上傳失敗:%s", e.getMessage())).build();
                e.printStackTrace();
            }
            // 返回數(shù)據(jù),完成此次請求
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    }
}

6.編寫客戶端代碼


import com.google.protobuf.ByteString;
import com.demo.grpc.file.FileServiceGrpc;
import com.demo.grpc.file.Request;
import com.demo.grpc.file.Response;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

/**
 * @Author: pengjunming
 * @Date:2020/1/8 9:14
 * @Description:
 */
public class Client {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8888;

    public static void main(String[] args) throws IOException, InterruptedException {
        Client client = new Client(HOST, PORT);
        client.upload("b.log", "D:/a.txt");
        client.shutdown();
    }

    private ManagedChannel managedChannel;

    private FileServiceGrpc.FileServiceBlockingStub blockingStub;

    public Client(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host, port).usePlaintext(true));
    }

    /**
     * 上傳文件
     * @param name 保存到服務(wù)端的文件名
     * @param path 要上傳的文件路徑
     * @throws IOException
     */
    public void upload(String name, String path) throws IOException {
        Request request = Request.newBuilder()
                .setName(name)
                // 文件 -> 字節(jié)碼數(shù)據(jù) -> ByteString
                .setFile(ByteString.copyFrom(getContent(path)))
                .build();
        Response response;
        try {
            response = blockingStub.upload(request);
            System.out.println(response.getMsg());
        } catch (StatusRuntimeException ex) {
        }
    }

    /**
     * 關(guān)閉客戶端
     */
    public void shutdown() throws InterruptedException {
        managedChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    Client(ManagedChannelBuilder<?> channelBuilder) {
        managedChannel = channelBuilder.build();
        blockingStub = FileServiceGrpc.newBlockingStub(managedChannel);
    }


    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 確保所有數(shù)據(jù)均被讀取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        System.out.println("生成文件長度" + buffer.length);
        return buffer;
    }

}

7.運行測試

  • 先運行服務(wù)端
  • 在D盤創(chuàng)建a.txt文件骡送,文件內(nèi)容隨意昂羡。(可以根據(jù)自己的程序修改路徑和文件名)
  • 運行客戶端
  • 檢查D:/tmp/new_a.txt 文件是否存在并且內(nèi)容是否跟a.txt一致

完畢,謝謝摔踱!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末虐先,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子派敷,更是在濱河造成了極大的恐慌蛹批,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件篮愉,死亡現(xiàn)場離奇詭異腐芍,居然都是意外死亡,警方通過查閱死者的電腦和手機潜支,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門甸赃,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人冗酿,你說我怎么就攤上這事埠对÷缍希” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵项玛,是天一觀的道長貌笨。 經(jīng)常有香客問我,道長襟沮,這世上最難降的妖魔是什么锥惋? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮开伏,結(jié)果婚禮上膀跌,老公的妹妹穿的比我還像新娘。我一直安慰自己固灵,他們只是感情好捅伤,可當(dāng)我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著巫玻,像睡著了一般丛忆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上仍秤,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天熄诡,我揣著相機與錄音,去河邊找鬼诗力。 笑死凰浮,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的姜骡。 我是一名探鬼主播导坟,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼屿良,長吁一口氣:“原來是場噩夢啊……” “哼圈澈!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起尘惧,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤康栈,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后喷橙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體啥么,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年贰逾,在試婚紗的時候發(fā)現(xiàn)自己被綠了悬荣。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡疙剑,死狀恐怖氯迂,靈堂內(nèi)的尸體忽然破棺而出践叠,到底是詐尸還是另有隱情,我是刑警寧澤嚼蚀,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布禁灼,位于F島的核電站,受9級特大地震影響轿曙,放射性物質(zhì)發(fā)生泄漏弄捕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一导帝、第九天 我趴在偏房一處隱蔽的房頂上張望守谓。 院中可真熱鬧,春花似錦您单、人聲如沸分飞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽譬猫。三九已至,卻和暖如春羡疗,著一層夾襖步出監(jiān)牢的瞬間染服,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工叨恨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留柳刮,地道東北人。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓痒钝,卻偏偏與公主長得像秉颗,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子送矩,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容