一、Maven的下载安装与配置
1.下载网址 http://maven.apache.org/download.cgi
选择下载二进制压缩归档文件 解压到任意目录下
2.配置环境变量
在系统变量新建两个变量M2_HOME和MAVEN_HOME,值为安装路径
编辑系统变量PATH,添加%M2_HOME%\bin
3.验证
命令行 mvn -v
4.配置settings.xml
增加本地仓库
在被注释掉的localRepository位置下一行 增加
自定义本地仓库路径(例:D:\software\gogogo)
配置阿里镜像仓库 在被注释掉的mirror下增加
aliyun-public
*
aliyun public
https://maven.aliyun.com/repository/public
aliyun-central
*
aliyun central
https://maven.aliyun.com/repository/central
aliyun-spring
*
aliyun spring
https://maven.aliyun.com/repository/spring
aliyun-spring-plugin
*
aliyun spring-plugin
https://maven.aliyun.com/repository/spring-plugin
aliyun-apache-snapshots
*
aliyun apache-snapshots
https://maven.aliyun.com/repository/apache-snapshots
aliyun-google
*
aliyun google
https://maven.aliyun.com/repository/google
aliyun-gradle-plugin
*
aliyun gradle-plugin
https://maven.aliyun.com/repository/gradle-plugin
aliyun-jcenter
*
aliyun jcenter
https://maven.aliyun.com/repository/jcenter
aliyun-releases
*
aliyun releases
https://maven.aliyun.com/repository/releases
aliyun-snapshots
*
aliyun snapshots
https://maven.aliyun.com/repository/snapshots
aliyun-grails-core
*
aliyun grails-core
https://maven.aliyun.com/repository/grails-core
aliyun-mapr-public
*
aliyun mapr-public
https://maven.aliyun.com/repository/mapr-public
二、配置IDEA
在File-Settings-Build,Execution,Development-Maven下
Maven home path :Maven解压路径
User Setting file:打开到刚刚修改的settings.xml文件
Local repository:本地仓库地址 修改完上一步后 这一条一般会默认出现
三、创建Maven项目工程
File-New-Project
配置pom.xml文件,导入gRPC的依赖和插件
4.0.0
com.wly
HelloWorld-gRPC-java
1.0-SNAPSHOT
com.google.protobuf
protobuf-java
3.8.0
io.grpc
grpc-all
1.14.0
io.grpc
grpc-netty-shaded
1.14.0
io.grpc
grpc-protobuf
1.14.0
io.grpc
grpc-stub
1.26.0
compile
kr.motd.maven
os-maven-plugin
1.5.0.Final
org.apache.maven.plugins
maven-compiler-plugin
3.6.1
1.6
org.xolstice.maven.plugins
protobuf-maven-plugin
0.5.1
com.wly.gRpc_helloworld.HelloWorld_Client.main
com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}
grpc-java
io.grpc:protoc-gen-grpc-java:1.36.0:exe:${os.detected.classifier}
compile-custom
compile
引入.proto文件
在main文件夹下,新建proto文件夹 在建好的proto文件夹下创建 helloworld.proto文件 增加内容
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
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) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
右击Maven.Projects\protobuf\protobuf:compile ,选择run,生成用于序列化的java文件。
再右击Maven.Projects\protobuf\protobuf:compile-custom,选择run,生成用于rpc的java代码。
可能出现的问题
解决方法:
Alt+Enter:选择Add Javaee 6 JARs to Module dependencies,下载相应的包
编写客户端和服务端代码
服务端代码:HelloWorld_Server.java
package com.wly.gRpc_helloworld;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.logging.Logger;
public class HelloWorld_Server {
private static final Logger logger = Logger.getLogger(HelloWorld_Server.class.getName());
private int port = 50051;
private Server server;
private void start() throws IOException{
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(){
System.err.println("*** shutting down gRPC server since JVM is shutting down");
HelloWorld_Server.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop(){
if (server != null){
server.shutdown();
}
}
// block 一直到退出程序
private void blockUntilShutdown() throws InterruptedException {
if (server != null){
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final HelloWorld_Server server = new HelloWorld_Server();
server.start();
server.blockUntilShutdown();
}
// 实现 定义一个实现服务接口的类
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req,StreamObserver responseObserver){
// HelloReply reply = HelloReply.newBuilder().setMessage(("{\"order\":\"1000\",\"operator\":\"China\",\"function\":\"start\"} "+req.getName())).build();
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello "+req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
System.out.println("Message from gRPC-Client:" + req.getName());
}
}
}
客户端代码: HelloWorld_Client.java
package com.wly.gRpc_helloworld;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HelloWorld_Client {
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
private static final Logger logger = Logger.getLogger(HelloWorld_Client.class.getName());
public HelloWorld_Client(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);
}
public void greet(String 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("Message from gRPC-Server: "+response.getMessage());
}
public static void main(String[] args) throws InterruptedException {
// HelloWorld_Client client = new HelloWorld_Client("192.168.2.122",9002);
HelloWorld_Client client = new HelloWorld_Client("127.0.0.1",50051);
try{
String user = "world";
if (args.length > 0){
user = args[0];
}
client.greet(user);
}finally {
client.shutdown();
}
}
}
运行
先运行HelloWorld_Server.java,再运行HelloWorld_Client.java
得到下图所示结果 证明通信成功