一、Maven的下载安装与配置
1.下载网址 http://maven.apache.org/download.cgi
选择下载二进制压缩归档文件 解压到任意目录下
2.配置环境变量
在系统变量新建两个变量M2_HOME和MAVEN_HOME,值为安装路径
编辑系统变量PATH,添加%M2_HOME%\bin
3.验证
命令行 mvn -v
4.配置settings.xml
增加本地仓库
在被注释掉的localRepository位置下一行 增加
<localRepository>自定义本地仓库路径(例:D:\software\gogogo)</localRepository>
配置阿里镜像仓库 在被注释掉的mirror下增加
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
<mirror>
<id>aliyun-public</id>
<mirrorOf>*</mirrorOf>
<name>aliyun public</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
<mirror>
<id>aliyun-central</id>
<mirrorOf>*</mirrorOf>
<name>aliyun central</name>
<url>https://maven.aliyun.com/repository/central</url>
</mirror>
<mirror>
<id>aliyun-spring</id>
<mirrorOf>*</mirrorOf>
<name>aliyun spring</name>
<url>https://maven.aliyun.com/repository/spring</url>
</mirror>
<mirror>
<id>aliyun-spring-plugin</id>
<mirrorOf>*</mirrorOf>
<name>aliyun spring-plugin</name>
<url>https://maven.aliyun.com/repository/spring-plugin</url>
</mirror>
<mirror>
<id>aliyun-apache-snapshots</id>
<mirrorOf>*</mirrorOf>
<name>aliyun apache-snapshots</name>
<url>https://maven.aliyun.com/repository/apache-snapshots</url>
</mirror>
<mirror>
<id>aliyun-google</id>
<mirrorOf>*</mirrorOf>
<name>aliyun google</name>
<url>https://maven.aliyun.com/repository/google</url>
</mirror>
<mirror>
<id>aliyun-gradle-plugin</id>
<mirrorOf>*</mirrorOf>
<name>aliyun gradle-plugin</name>
<url>https://maven.aliyun.com/repository/gradle-plugin</url>
</mirror>
<mirror>
<id>aliyun-jcenter</id>
<mirrorOf>*</mirrorOf>
<name>aliyun jcenter</name>
<url>https://maven.aliyun.com/repository/jcenter</url>
</mirror>
<mirror>
<id>aliyun-releases</id>
<mirrorOf>*</mirrorOf>
<name>aliyun releases</name>
<url>https://maven.aliyun.com/repository/releases</url>
</mirror>
<mirror>
<id>aliyun-snapshots</id>
<mirrorOf>*</mirrorOf>
<name>aliyun snapshots</name>
<url>https://maven.aliyun.com/repository/snapshots</url>
</mirror>
<mirror>
<id>aliyun-grails-core</id>
<mirrorOf>*</mirrorOf>
<name>aliyun grails-core</name>
<url>https://maven.aliyun.com/repository/grails-core</url>
</mirror>
<mirror>
<id>aliyun-mapr-public</id>
<mirrorOf>*</mirrorOf>
<name>aliyun mapr-public</name>
<url>https://maven.aliyun.com/repository/mapr-public</url>
</mirror>
</mirrors>
二、配置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的依赖和插件
<?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.wly</groupId>
<artifactId>HelloWorld-gRPC-java</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.14.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.14.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.14.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.26.0</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.1</version>
<configuration>
<mainClass>com.wly.gRpc_helloworld.HelloWorld_Client.main</mainClass>
<protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.36.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile-custom</goal>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
引入.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<HelloReply> 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
得到下图所示结果 证明通信成功