thrift java示例

thrift java示例

使用IntelliJ IDEA作为开发工具;

增加proto文件夹,里面写上sayHello.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "grpc.example";
option java_outer_classname = "HelloProto";
option objc_class_prefix = "HLW";

package service;

service HelloService{
    rpc SayHello (HelloRequest) returns (HelloResponse){}
}

message HelloRequest{
    string name = 1;
}

message HelloResponse{
    string message = 1;
}

pom.xml文件:

<?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>com.stono</groupId>
    <artifactId>grpc-2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <os.detection.classifierWithLikes>debian,rhel</os.detection.classifierWithLikes>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

    <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>
                    <protocArtifact>com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>os.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

在Maven Projects中,进行protobuf:compile,protobuf:compile-custom;

生成grpc-java和java源文件;

然后编写客户端、服务端程序:

package com.grpc;

import grpc.example.HelloRequest;
import grpc.example.HelloResponse;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import grpc.example.HelloSerivceGrpc;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

public class HelloServer {
    private int port = 50051;
    private Server server;
    private void start() throws IOException{
        server = ServerBuilder.forPort(port)
                .addService(new HelloServiceImpl())
                .build()
                .start();
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run(){
                HelloServer.this.stop();
            }
        });
    }
    private void stop(){
        if(server!=null){
            server.shutdown();
        }
    }
    private void blockUntilShutdown() throws InterruptedException{
        if(server != null){
            server.awaitTermination();
        }
    }
    private class HelloServiceImpl extends HelloSerivceGrpc.HelloSerivceImplBase{
        public void sayHello(HelloRequest req, StreamObserver<HelloResponse> responseObserver){
            HelloResponse reply = HelloResponse.newBuilder().setMessage("Hello, "+req.getName()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    public static void main(String[] args) throws Exception {
        final HelloServer server = new HelloServer();
        server.start();
        server.blockUntilShutdown();
    }
}
package com.grpc;

import grpc.example.HelloRequest;
import grpc.example.HelloResponse;
import io.grpc.ManagedChannel;
import grpc.example.HelloSerivceGrpc;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

public class HelloClient {
    private final ManagedChannel channel;
    private final HelloSerivceGrpc.HelloSerivceBlockingStub blockingStub;
    public HelloClient(String host,int port){
        channel = ManagedChannelBuilder.forAddress(host,port)
                .usePlaintext(true)
                .build();
        blockingStub = HelloSerivceGrpc.newBlockingStub(channel);
    }
    public void shutdown() throws InterruptedException{
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }
    public String sayHello(String name){
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloResponse response = blockingStub.sayHello(request);
        return response.getMessage();
    }

    public static void main(String[] args) throws Exception {
        HelloClient client = new HelloClient("127.0.0.1",50051);
        String content = client.sayHello("stono");
        System.out.println(content);
        client.shutdown();
    }
}

注意把生成的代码文件夹作为source folder;

然后就可以运行了;

原文地址:https://www.cnblogs.com/stono/p/8284496.html