ptotobuf grpc java端通信

首先 定义一份.ptoto源文件 
syntax = "proto3"; 
option java_package = "com.bubukj.proto";  //设置java对应的package  
option java_multiple_files = true; //建议设置为true,这样会每个对象放在一个文件中,否则所有对象都在一个java文件中

//公司列表
message CompanyList{
     string id = 1;
	 int32 type = 2;
	 string headimg = 3;
	 string service = 4;
	 string realName = 5;
	 string companyName = 6;
	 string address = 7;
	 string count = 8;
}

//banner图
message BannerList{
    string id = 1;
	string url = 2;
}

message AskbannerList{
    string id = 1;
	string url = 2;
}


message TaskList{
   string id = 1;
   string title = 2;
   string priceMin = 3;
   string priceMax = 4;
   string lifecycle = 5;
   string workType = 6;
   string userHeadimg = 7;
   string userName = 8;
   string companyName = 9;
   string count = 10;
}


message SkillList{
	string id = 1;
	string title = 2;
	string img = 3;
}

message HomeRequest{
    string id = 1;
}

message Home{
      message Wisdom{
	       SkillList skiList = 1;
		   repeated CompanyList comList = 2;
	  }
	  message TaskHall{
	       SkillList skiList = 1;
		   repeated CompanyList comList = 2;
	  }
	  
	  repeated BannerList banList = 3;
	  
	  repeated AskbannerList askbanList = 4;
	  
	  repeated TaskList taskList = 5;
	  
	  repeated CompanyList companyList = 6;

}

service HuibaoHome{
  rpc GetHome(HomeRequest) returns(Home){}
}






其次新建 一个Maven工程:

找到pom.xml文件 往其中加入以下 JARs :

<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-netty</artifactId>
  <version>1.8.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-protobuf</artifactId>
  <version>1.8.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-stub</artifactId>
  <version>1.8.0</version>
</dependency>

再添加编译protobuf的插件

<build>
  <extensions>
    <extension>
      <groupId>kr.motd.maven</groupId>
      <artifactId>os-maven-plugin</artifactId>
      <version>1.5.0.Final</version>
    </extension>
  </extensions>
  <plugins>
    <plugin>
      <groupId>org.xolstice.maven.plugins</groupId>
      <artifactId>protobuf-maven-plugin</artifactId>
      <version>0.5.0</version>
      <configuration>
        <protocArtifact>com.google.protobuf:protoc:3.5.0:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.8.0:exe:${os.detected.classifier}</pluginArtifact>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>compile-custom</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>


最后把.ptoto源文件随便放到一个目录下:

在<configuration></configuration> 中 加 上  <protoSourceRoot>src/main/</protoSourceRoot>  写上.ptoto的路径即可  再用maven编译  就可得到Grpcjava文件


再自己写服务端与客户端:

package com.bubukj.proto.service;

import java.io.IOException;
import java.util.logging.Logger;

import javax.print.attribute.standard.RequestingUserName;

import com.bubukj.proto.Home;
import com.bubukj.proto.HomeRequest;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

public class HuibaoServer {
	
	private static final Logger logger = Logger.getLogger(HuibaoServer.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(new HuibaoImpl())
	        .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");
	        HuibaoServer.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 HuibaoServer server = new HuibaoServer();
	    server.start();
	    server.blockUntilShutdown();
	  }
	  
	  
	  private class HuibaoImpl extends HuibaoHomeGrpc.HuibaoHomeImplBase {
		  
		@Override
		public void getHome(HomeRequest request,
				StreamObserver<Home> responseObserver) {
			// TODO Auto-generated method stub
			System.out.println("来了吗??"+request.getId());
			super.getHome(request, responseObserver);
		}
		  
		  
	  }
	 
	 

}


package com.bubukj.proto.demo;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.bubukj.proto.Home;
import com.bubukj.proto.HomeRequest;
import com.bubukj.proto.service.HuibaoHomeGrpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

public class HuibaoClient {
	
	
	private static final Logger logger = Logger.getLogger(HuibaoClient.class.getName());

	  private final ManagedChannel channel;
	  private final HuibaoHomeGrpc.HuibaoHomeBlockingStub blockingStub;

	  /** Construct client connecting to HelloWorld server at {@code host:port}. */
	  public HuibaoClient(String host, int port) {
	    channel = ManagedChannelBuilder.forAddress(host, port)
	        .usePlaintext(true)
	        .build();
	    blockingStub = HuibaoHomeGrpc.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 + " ...");
	    HomeRequest request = HomeRequest.newBuilder().setId(name).build();
	    Home response;
	    try {
	    	response = blockingStub.getHome(request);
	      //response = blockingStub.sayHello(request);
	    } catch (StatusRuntimeException e) {
	      logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
	      return;
	    }
	    logger.info("Greeting: " + response.getSerializedSize());
	  }

	  /**
	   * 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 {
	    HuibaoClient client = new HuibaoClient("localhost", 50051);
	    try {
	      /* Access a service running on the local machine on port 50051 */
	      String user = "xiaotian";
	      if (args.length > 0) {
	        user = args[0]; /* Use the arg as the name to greet if provided */
	      }
	      client.greet(user);
	    } finally {
	      client.shutdown();
	    }
	  }

}


执行main方法 就可通信

源码地址:https://github.com/guoguo250/guoguo2 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值