java grpc_gRPC-Java实践

1.新建一个Maven工程,添加gRPC相关依赖

io.grpc

grpc-all

1.20.0

2.添加protocol buffers 编译插件

kr.motd.maven

os-maven-plugin

1.4.1.Final

org.springframework.boot

spring-boot-maven-plugin

org.xolstice.maven.plugins

protobuf-maven-plugin

0.6.1

com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}

grpc-java

io.grpc:protoc-gen-grpc-java:0.15.0:exe:${os.detected.classifier}

/Users/sgf/Documents/yang/MyWork/protoc-3.7.1-osx-x86_64/bin/protoc

compile

compile-custom

2.1注意

e60783dbf3b2

image.png

第二个框框中的地址是我本地protoc的编译执行程序所在地址

e60783dbf3b2

image.png

可在此下载对应版本的编译执行程序

这是我的文件结构,重要的文件都框出来了

e60783dbf3b2

3.编写.proto文件

syntax = "proto3";

option java_multiple_files = true;

option java_package = "com.page.awesome.dto.proto";

option java_outer_classname = "HelloWorldProto";

option objc_class_prefix = "HLW";

//package helloworld;

// The greeting service definition.

service Greeter {

// Sends a greeting

rpc SayHello (HelloRequest) returns (HelloReply) {

}

// Sends another greeting

rpc SayHelloAgain (HelloRequest) returns (HelloReply) {

}

}

// The request message containing the user's name.

message HelloRequest {

string name = 1;

}

// The response message containing the greetings

message HelloReply {

string message = 1;

}

4.编译

e60783dbf3b2

image.png

图中的两个都需要,然后就完成了。

e60783dbf3b2

image.png

5.创建HelloWorldClient和HelloWorldServer

/*

* Copyright 2015 The gRPC Authors

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package com.page.awesome.hello;

import com.page.awesome.dto.proto.GreeterGrpc;

import com.page.awesome.dto.proto.HelloReply;

import com.page.awesome.dto.proto.HelloRequest;

import io.grpc.ManagedChannel;

import io.grpc.ManagedChannelBuilder;

import io.grpc.StatusRuntimeException;

import java.util.concurrent.TimeUnit;

import java.util.logging.Level;

import java.util.logging.Logger;

/**

* A simple client that requests a greeting from the {@link HelloWorldServer}.

*/

public class HelloWorldClient {

private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());

private final ManagedChannel channel;

private final GreeterGrpc.GreeterBlockingStub blockingStub;

/** Construct client connecting to HelloWorld server at {@code host:port}. */

public HelloWorldClient(String host, int port) {

this(ManagedChannelBuilder.forAddress(host, port)

// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid

// needing certificates.

.usePlaintext()

.build());

}

/** Construct client for accessing HelloWorld server using the existing channel. */

HelloWorldClient(ManagedChannel channel) {

this.channel = channel;

blockingStub = GreeterGrpc.newBlockingStub(channel);

}

public void shutdown() throws InterruptedException {

channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);

}

/** Say hello to server. */

public void greet(String name) {

logger.info("client request ==============" + name + " ...");

HelloRequest request = HelloRequest.newBuilder().setName(name).build();

HelloReply response;

try {

response = blockingStub.sayHello(request);

} catch (StatusRuntimeException e) {

logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());

return;

}

logger.info("response: ===============" + response.getMessage());

}

/**

* Greet server. If provided, the first element of {@code args} is the name to use in the

* greeting.

*/

public static void main(String[] args) throws Exception {

HelloWorldClient client = new HelloWorldClient("localhost", 50051);

try {

/* Access a service running on the local machine on port 50051 */

String user = "world===============";

if (args.length > 0) {

user = args[0]; /* Use the arg as the name to greet if provided */

}

client.greet(user);

} finally {

client.shutdown();

}

}

}

/*

* Copyright 2015 The gRPC Authors

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package com.page.awesome.hello;

import com.page.awesome.dto.proto.GreeterGrpc;

import com.page.awesome.dto.proto.HelloReply;

import com.page.awesome.dto.proto.HelloRequest;

import io.grpc.Server;

import io.grpc.ServerBuilder;

import io.grpc.stub.StreamObserver;

import java.io.IOException;

import java.util.logging.Logger;

/**

* Server that manages startup/shutdown of a {@code Greeter} server.

*/

public class HelloWorldServer {

private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());

private Server server;

private void start() throws IOException {

/* The port on which the server should run */

int port = 50051;

server = ServerBuilder.forPort(port)

.addService(new GreeterImpl())

.build()

.start();

logger.info("Server started, listening on " + port);

Runtime.getRuntime().addShutdownHook(new Thread() {

@Override

public void run() {

// Use stderr here since the logger may have been reset by its JVM shutdown hook.

System.err.println("*** shutting down gRPC server since JVM is shutting down");

HelloWorldServer.this.stop();

System.err.println("*** server shut down");

}

});

}

private void stop() {

if (server != null) {

server.shutdown();

}

}

/**

* Await termination on the main thread since the grpc library uses daemon threads.

*/

private void blockUntilShutdown() throws InterruptedException {

if (server != null) {

server.awaitTermination();

}

}

/**

* Main launches the server from the command line.

*/

public static void main(String[] args) throws IOException, InterruptedException {

final HelloWorldServer server = new HelloWorldServer();

server.start();

server.blockUntilShutdown();

}

static class GreeterImpl extends GreeterGrpc.GreeterImplBase {

@Override

public void sayHello(HelloRequest req, StreamObserver responseObserver) {

HelloReply reply = HelloReply.newBuilder().setMessage("Hello ++++++++++++++++" + req.getName()).build();

responseObserver.onNext(reply);

responseObserver.onCompleted();

}

}

}

6.运行

先运行HelloWorldServer,然后运行HelloWorldClient

e60783dbf3b2

image.png

e60783dbf3b2

image.png

完成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值