原文地址: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简单例子的更多相关文章
-
Java RMI简单例子HelloWorld
Java RMI 指的是远程方法调用 (Remote Method Invocation).它是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法.可以用此方 ...
-
java 多线程简单例子
实现线程的方式是一,继承Thread类,重写父类的run()方法 二,实现接口Runnable中的run()方法. 下面是简单的例子 例子1:银行存取钱问题 package com.direct.de ...
-
fastdfs5.x Java客户端简单例子
下载源码, 使用maven编译并安装 https://github.com/happyfish100/fastdfs-client-java.git 新建maven工程,引入fastdfs-clien ...
-
java多态简单例子
/* 对象的多态性:动物 x = new 猫(); 函数的多态性:函数重载.重写 1.多态的体现 父类的引用指向了自己的子类对象 父类的引用也可以接收自己的对象 2.多态的前提 必须是类与类之间只有关 ...
-
java socket编程开发简单例子 与 nio非阻塞通道
基本socket编程 1.以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理 2.以下代码使用了1.8新特 ...
-
java 使用 comet4j 主动向客户端推送信息 简单例子
[背景] 今天,一个前端的师弟问我怎样做实时聊天窗口,我毫不犹豫地说:在前台定时访问服务端呀!师弟默默地百度了一番,最后告诉我,有一种技术是后服务端动推送信息给客户端的,这种技术的名字叫comet,我 ...
-
Java中死锁的简单例子及其避免
死锁:当一个线程永远地持有一个锁,并且其他线程都尝试获得这个锁时,那么它们将永远被阻塞.比如,线程1已经持有了A锁并想要获得B锁的同时,线程2持有B锁并尝试获取A锁,那么这两个线程将永远地等待下去. ...
-
(转)Java中使用正则表达式的一个简单例子及常用正则分享
转自:http://www.jb51.net/article/67724.htm 这篇文章主要介绍了Java中使用正则表达式的一个简单例子及常用正则分享,本文用一个验证Email的例子讲解JAVA中如 ...
-
java爬取网页内容 简单例子(2)——附jsoup的select用法详解
[背景] 在上一篇博文java爬取网页内容 简单例子(1)——使用正则表达式 里面,介绍了如何使用正则表达式去解析网页的内容,虽然该正则表达式比较通用,但繁琐,代码量多,现实中想要想出一条简单的正则表 ...
随机推荐
-
get方式提交中文乱码解决
get方式提交中文时会乱码,过滤器只过滤post请求,此时可修改tomcat配置文件server.xml,为Connector添加属性URIEncoding="utf-8". ec ...
-
Codeforces Perfect Pair (JAVA)
http://codeforces.com/problemset/problem/317/A 题意:给两个数字,可以两数相加去替换其中一个数字.问要做多少次,可以让两个数字钟至少一个 >= 目标 ...
-
ueditor上传图片到七牛云存储(form api,java)
转:http://my.oschina.net/duoduo3369/blog/174655 ueditor上传图片到七牛云存储 ueditor结合七牛传图片 七牛的试炼 开发前的准备与注意事项说明 ...
-
Codeforces Round #250 (Div. 1) D. The Child and Sequence 线段树 区间取摸
D. The Child and Sequence Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest ...
-
sql查询当天数据
向数据库中添加日期 MS SQL SERVER: NSERT into student(studentid,time1)values('15',getdate()); MY SQLinsert int ...
-
【PHP】PHP获得第一章
一,PHP上部和下部壳体敏感 1)所有的用户定义的函数.类和keyword敏感. 例如以下结果输出一致: echo "hello world" Echo "hello ...
-
html模板中的数字保留两位小数
<script> //html模板中的数字保留两位小数 function formatCurrency(num) { num = num.toString().replace(/\$|\, ...
-
Codeforces 818B Permutation Game
首先看一下题目 B. Permutation Game time limit per test 1 second memory limit per test 256 megabytes input s ...
-
iOS隐藏状态栏
1.整个项目隐藏状态栏 在Targets->General->勾选中Hide status bar . 整个项目隐藏状态栏 2.单个界面隐藏状态栏,例如登录注册页面 1.首先在info.p ...
-
BZOJ4180:字符串计数(SAM,二分,矩阵乘法)
Description SD有一名神犇叫做Oxer,他觉得字符串的题目都太水了,于是便出了一道题来虐蒟蒻yts1999. 他给出了一个字符串T,字符串T中有且仅有4种字符 'A', 'B', 'C', ...