原文地址:http://blog.csdn.net/jek123456/article/details/53465033

用eclipse新建一个maven项目,Id信息如下

<groupId>com.mingluck.test</groupId>
<artifactId>grpc</artifactId>

创建如下的目录结构(包括文件) 
 
看下面的test.proto的内容:

syntax = "proto3";
package grpc;
option java_package = "com.mingluck.grpc";
option java_outer_classname = "HelloWorldServiceProto";
option java_multiple_files = true; //服务端接口类
service Greeter {
//服务端接口方法
rpc SayHello (HelloRequest) returns (HelloReply) {}
} //请求参数
message HelloRequest {
string name = 1;
string sex = 2;
} //响应参数
message HelloReply {
string message = 1;
}

其中java_package 指定了生成的类的包名 
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.mingluck.test</groupId>
<artifactId>grpc</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.0.0</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</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>
<!-- protobuf -->
<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-beta-2:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:0.14.0:exe:${os.detected.classifier}</pluginArtifact>
<protoSourceRoot>src/main/resources/proto</protoSourceRoot>
</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>
</project>

然后在cmd窗口中切换到项目pom.xml文件所在的目录,运行mvn compile命令,运行命令后目录结构会变成如下 
 
接下来可以写代码了,先实现服务端程序,HelloWorldServer.java

package com.mingluck.grpc;
/**
* Created by Darren on 2016/11/11.
*/
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver; import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger; public class HelloWorldServer {
private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName()); /* The port on which the server should run */
private int port = 50051;
private Server server; private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(GreeterGrpc.bindService(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();
} private class GreeterImpl implements GreeterGrpc.Greeter {
/** 原子Integer */
public AtomicInteger count = new AtomicInteger(0); @Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
System.out.println("call sayHello");
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName() + req.getSex()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
System.out.println(count.incrementAndGet() + Thread.currentThread().getName());
}
}
}

注意sayHello方法的重写 
接下来实现HelloWorldClient.java

package com.mingluck.grpc;

/**
* Created by Darren on 2016/11/11.
*/
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) { channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext(true)
.build();
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("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).setSex(" 女").build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + 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 { String user = "world";
if (args.length > 0) {
user = args[0];
}
client.greet(user);
} finally {
client.shutdown();
}
}
}

分别运行服务端和客户端,会看到rpc调用成功。 
为了防止客户端不断调用带来的开销(短连接),下面的例子给出了连接池的方式,代码如下

package com.mingluck.grpc;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig; /**
* Created by darren on 2016/11/14.
*/
public class HelloWorldClientFactory extends BasePooledObjectFactory<HelloWorldClient> { @Override
public HelloWorldClient create() throws Exception {
return new HelloWorldClient("localhost", 50051);
} @Override
public PooledObject<HelloWorldClient> wrap(HelloWorldClient client) {
return new DefaultPooledObject<HelloWorldClient>(client);
} @Override
public void destroyObject(PooledObject<HelloWorldClient> p) throws Exception {
HelloWorldClient client = p.getObject();
client.shutdown();
super.destroyObject(p);
} public static void main(String[] args) throws Exception { /** 连接池的配置 */
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); /** 下面的配置均为默认配置,默认配置的参数可以在BaseObjectPoolConfig中找到 */
poolConfig.setMaxTotal(8); // 池中的最大连接数
poolConfig.setMinIdle(0); // 最少的空闲连接数
poolConfig.setMaxIdle(8); // 最多的空闲连接数
poolConfig.setMaxWaitMillis(-1); // 当连接池资源耗尽时,调用者最大阻塞的时间,超时时抛出异常 单位:毫秒数
poolConfig.setLifo(true); // 连接池存放池化对象方式,true放在空闲队列最前面,false放在空闲队列最后
poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L); // 连接空闲的最小时间,达到此值后空闲连接可能会被移除,默认即为30分钟
poolConfig.setBlockWhenExhausted(true); // 连接耗尽时是否阻塞,默认为true /** 连接池创建 */
GenericObjectPool<HelloWorldClient> objectPool = new GenericObjectPool<HelloWorldClient>(new HelloWorldClientFactory(), poolConfig); new Thread(makeTask(objectPool)).start();
new Thread(makeTask(objectPool)).start();
new Thread(makeTask(objectPool)).start();
new Thread(makeTask(objectPool)).start(); Thread.sleep(100000); } private static Runnable makeTask(GenericObjectPool<HelloWorldClient> objectPool){
return () -> {
HelloWorldClient client = null;
try {
client = objectPool.borrowObject(); } catch (Exception e) {
e.printStackTrace();
}
try {
String req = "world!";
client.greet(req);
} finally {
/** 将连接对象返回给连接池 */
objectPool.returnObject(client);
}
};
}
}

java grpc简单例子的更多相关文章

  1. Java RMI简单例子HelloWorld

    Java RMI 指的是远程方法调用 (Remote Method Invocation).它是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法.可以用此方 ...

  2. java 多线程简单例子

    实现线程的方式是一,继承Thread类,重写父类的run()方法 二,实现接口Runnable中的run()方法. 下面是简单的例子 例子1:银行存取钱问题 package com.direct.de ...

  3. fastdfs5.x Java客户端简单例子

    下载源码, 使用maven编译并安装 https://github.com/happyfish100/fastdfs-client-java.git 新建maven工程,引入fastdfs-clien ...

  4. java多态简单例子

    /* 对象的多态性:动物 x = new 猫(); 函数的多态性:函数重载.重写 1.多态的体现 父类的引用指向了自己的子类对象 父类的引用也可以接收自己的对象 2.多态的前提 必须是类与类之间只有关 ...

  5. java socket编程开发简单例子 与 nio非阻塞通道

    基本socket编程 1.以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理 2.以下代码使用了1.8新特 ...

  6. java 使用 comet4j 主动向客户端推送信息 简单例子

    [背景] 今天,一个前端的师弟问我怎样做实时聊天窗口,我毫不犹豫地说:在前台定时访问服务端呀!师弟默默地百度了一番,最后告诉我,有一种技术是后服务端动推送信息给客户端的,这种技术的名字叫comet,我 ...

  7. Java中死锁的简单例子及其避免

    死锁:当一个线程永远地持有一个锁,并且其他线程都尝试获得这个锁时,那么它们将永远被阻塞.比如,线程1已经持有了A锁并想要获得B锁的同时,线程2持有B锁并尝试获取A锁,那么这两个线程将永远地等待下去. ...

  8. (转)Java中使用正则表达式的一个简单例子及常用正则分享

    转自:http://www.jb51.net/article/67724.htm 这篇文章主要介绍了Java中使用正则表达式的一个简单例子及常用正则分享,本文用一个验证Email的例子讲解JAVA中如 ...

  9. java爬取网页内容 简单例子(2)——附jsoup的select用法详解

    [背景] 在上一篇博文java爬取网页内容 简单例子(1)——使用正则表达式 里面,介绍了如何使用正则表达式去解析网页的内容,虽然该正则表达式比较通用,但繁琐,代码量多,现实中想要想出一条简单的正则表 ...

随机推荐

  1. python删除x天前文件及文件夹

    #!/usr/bin/env python # -*- coding:utf-8 -*- import os, time, sys, shutil def delFiles(beforeSec, di ...

  2. windows上如何安装Sqlite

    一.安装 下载地址:http://www.sqlite.org/download.html 将Precompiled Binaries for Windows下的包下载下来sqlite-dll-win ...

  3. PhpStorm 10.0.3 下载安装与汉化

    https://www.7down.com/soft/229568.html 2JA97R55MG-eyJsaWNlbnNlSWQiOiIySkE5N1I1NU1HIiwibGljZW5zZWVOYW ...

  4. Python中表达式和语句及for、while循环练习

    Python中表达式和语句及for.while循环练习 1)表达式 常用的表达式操作符: x + y, x - y x * y, x / y, x // y, x % y 逻辑运算: x or y, ...

  5. 32位ubuntu14.04手动编译hadoop2.6.0

    下载官方编译好的包安装老是报错:Unable to load native-hadoop library for your platform 用file命令查看发现官方包里的libhadoop.so. ...

  6. solr跨core查询

    参考文档:这里的跨core不使用solrcloud http://wiki.apache.org/solr/CoreAdmin 注意:跨core查询功能相比单core查询,是有限制的   只需要在ur ...

  7. java 工具类 static

    http://wenwen.sogou.com/z/q526955586.htm 工具类其实就是提供了一些公共的函数,方便其他类去调用,函数都写成static一方面是因为方便,另一方面是工具类的函数是 ...

  8. C细节学习

    字符串ascii码值比较compress函数;

  9. ES6系列_5之字符串模版

    1.字符串模板对比引入: (1).之前我们也可以使用JavaScript输出模版字符串,通常是下面这样的: var restult= "姓名: <b>"+person. ...

  10. Selenium Webdriver——Xpath轴定位(preceding)

     1.preceding-sibling 选取当前节点之前的所有同级节点 text=出发之前的同级节点: 2.preceding 选取当前节点开始标签之前的所有节点 text=出发节点标签之前的所有i ...