赞
踩
nacos 2.0以后,客户端服务端交互由HTTP改为GRPC,所以看了下grpc,grpc的简介就不写了,网上一搜都能看到,这里用java写一个grpc的小demo
创建一个空的maven项目,名字叫:grpc-java
添加protobuf相关依赖
<?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>org.my</groupId> <artifactId>grpc-java</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <grpc-version>1.20.0</grpc-version> </properties> <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-core</artifactId> <version>${grpc-version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty-shaded</artifactId> <version>${grpc-version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc-version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc-version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> <optional>true</optional> </dependency> </dependencies> <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.7.1:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact> <protoSourceRoot>src/main/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> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
syntax = "proto3"; option java_package = "com.my.grpc.protobuf"; option java_multiple_files = false; /*** service处理类 */ service BaseService { //返回的data是对象 rpc method(Request) returns (Response){} //返回的data是集合 rpc listMethod(Request) returns (ListResponse){} } //请求类 message Request{ //请求类型 string type = 1; //参数 string name = 2; } //用户信息 message User{ int64 id=1; string name=2; string password=3; string address=4; } message GirFriend{ string name=1; string age=2; string address=3; } //返回数据 message Response { string code = 1; string message = 2; bytes data=3; } //集合返回数据 message ListResponse { string code = 1; string message = 2; repeated bytes data=3; }
生成目录如下,移动到项目中
添加GrpcService类,继承BaseServiceImplBase
重写method与listMethod
public class GrpcService extends BaseServiceGrpc.BaseServiceImplBase{ @Override public void method(Data.Request request, io.grpc.stub.StreamObserver<Data.Response> responseObserver) { Data.Response response=null; if(request.getType().equals("user")){ response=getUser(request); } responseObserver.onNext(response); responseObserver.onCompleted(); } @Override public void listMethod(Data.Request request, io.grpc.stub.StreamObserver<Data.ListResponse> responseObserver) { Data.ListResponse response=null; response=getGirlFriends(request); responseObserver.onNext(response); responseObserver.onCompleted(); } public Data.Response getUser(Data.Request request){ if("张三".equals(request.getName())){ Data.User user= Data.User.newBuilder() .setId(1L) .setName("张三") .setAddress("北京市东城区南竹杆胡同2号银河SOHO") .setPassword("123456") .build(); return Data.Response.newBuilder() .setCode("200") .setMessage("成功") .setData(user.toByteString()) .build(); }else{ return Data.Response.newBuilder() .setCode("404") .setMessage("无此用户") .build(); } } public Data.ListResponse getGirlFriends(Data.Request request){ if("张三".equals(request.getName())){ List<ByteString> list=new ArrayList<>(); Data.GirFriend girFriend= Data.GirFriend.newBuilder() .setName("迪丽热巴") .setAge("25") .setAddress("新疆维吾尔自治区乌鲁木齐市") .build(); list.add(girFriend.toByteString()); girFriend= Data.GirFriend.newBuilder() .setName("杨幂") .setAge("30") .setAddress("北京市宣武区") .build(); list.add(girFriend.toByteString()); girFriend= Data.GirFriend.newBuilder() .setName("项思醒") .setAge("24") .setAddress("杭州") .build(); list.add(girFriend.toByteString()); Data.ListResponse.Builder builder = Data.ListResponse.newBuilder() .setCode("200") .setMessage("成功"); for (int i = 0; i < list.size(); i++) { builder.addData(list.get(i)); } return builder.build(); }else{ return Data.ListResponse.newBuilder() .setCode("404") .setMessage("无此用户") .build(); } } }
public class GrpcServer { static CountDownLatch cd=new CountDownLatch(1); static Server server; public static void main(String[] args) throws IOException, InterruptedException { System.out.println("grpc server start ......."); //绑定端口 //设置处理服务的类 server = ServerBuilder.forPort(8901) .addService(new GrpcService()) .build(); server.start(); System.out.println("grpc server started ......."); Runtime.getRuntime().addShutdownHook(new Thread(() -> { //项目被关闭触发 stop(); System.out.println("grpc server shutdown ......."); })); cd.await(); } public static void stop(){ if(server!=null){ server.shutdownNow(); } cd.countDown(); } }
public class GrpcClient { ManagedChannel channel; public BaseServiceGrpc.BaseServiceBlockingStub blockingStub; final ThreadPoolExecutor grpcExecutor ; public GrpcClient() { grpcExecutor = new ThreadPoolExecutor(Runtime.getRuntime() .availableProcessors() * 8, Runtime.getRuntime().availableProcessors() * 8, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10000), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("my-grpc-client-executor-%d") .build()); } public void connectToServer(String serverIp, int serverPort){ ManagedChannelBuilder<?> o = ManagedChannelBuilder.forAddress(serverIp, serverPort) .executor(grpcExecutor) .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .maxInboundMessageSize(10 * 1024 * 1024) .keepAliveTime(6 * 60 * 1000, TimeUnit.MILLISECONDS) .usePlaintext(); ManagedChannelBuilder builder = ManagedChannelBuilder.forAddress(serverIp, serverPort). maxInboundMessageSize(2147483647). usePlaintext(); this.channel = builder.intercept(new ClientInterceptor[]{}).build(); blockingStub = BaseServiceGrpc.newBlockingStub(channel); } public Data.User getUser(String userName) throws InvalidProtocolBufferException { Data.Request request= Data.Request.newBuilder() .setType("user") .setName(userName) .build(); Data.Response response = this.blockingStub.method(request); System.out.println(String.format("code:%s,message:%s",response.getCode(),response.getMessage())); Data.User user =null; if("200".equals(response.getCode())) { user = Data.User.parseFrom(response.getData()); System.out.println(String.format("姓名:%s,地址:%s", user.getName(), user.getAddress())); } return user; } public List<Data.GirFriend> getFriends(String userName) throws InvalidProtocolBufferException { Data.Request request= Data.Request.newBuilder() .setType("friends") .setName(userName) .build(); Data.ListResponse listResponse = this.blockingStub.listMethod(request); System.out.println(String.format("code:%s,message:%s",listResponse.getCode(),listResponse.getMessage())); List<Data.GirFriend> girFriends =new ArrayList<>(); if("200".equals(listResponse.getCode())) { for (ByteString bytes : listResponse.getDataList()) { Data.GirFriend girFriend = Data.GirFriend.parseFrom(bytes); girFriends.add(girFriend); } } return girFriends; } public static void main(String[] args) throws InvalidProtocolBufferException { GrpcClient grpcClient = new GrpcClient(); grpcClient.connectToServer("127.0.0.1", 8901); Data.User user = grpcClient.getUser("张三"); List<Data.GirFriend> friends = grpcClient.getFriends("张三"); for (int i = 0; i <friends.size() ; i++) { System.out.println(String.format("第%s个女朋友:%s,住址:%s",i+1, friends.get(i).getName(),friends.get(i).getAddress())); } } }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。