|
| 1 | +/* |
| 2 | + * Copyright 2023 The gRPC Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.grpc.examples.preserialized; |
| 18 | + |
| 19 | +import io.grpc.BindableService; |
| 20 | +import io.grpc.Grpc; |
| 21 | +import io.grpc.InsecureServerCredentials; |
| 22 | +import io.grpc.MethodDescriptor; |
| 23 | +import io.grpc.Server; |
| 24 | +import io.grpc.ServerCallHandler; |
| 25 | +import io.grpc.ServerMethodDefinition; |
| 26 | +import io.grpc.ServerServiceDefinition; |
| 27 | +import io.grpc.ServiceDescriptor; |
| 28 | +import io.grpc.examples.helloworld.GreeterGrpc; |
| 29 | +import io.grpc.examples.helloworld.HelloReply; |
| 30 | +import io.grpc.examples.helloworld.HelloRequest; |
| 31 | +import io.grpc.stub.ServerCalls; |
| 32 | +import io.grpc.stub.StreamObserver; |
| 33 | +import java.io.IOException; |
| 34 | +import java.util.concurrent.TimeUnit; |
| 35 | +import java.util.logging.Logger; |
| 36 | + |
| 37 | +/** |
| 38 | + * Server that provides a {@code Greeter} service, but that uses a pre-serialized response. This is |
| 39 | + * a performance optimization that can be useful if you read the response from on-disk or a database |
| 40 | + * where it is already serialized, or if you need to send the same complicated message to many |
| 41 | + * clients. The same approach can avoid deserializing requests, to be stored in a database. This |
| 42 | + * adjustment is server-side only; the client is unable to detect the differences, so this server is |
| 43 | + * fully-compatible with the normal {@link HelloWorldClient}. |
| 44 | + */ |
| 45 | +public class PreSerializedServer { |
| 46 | + private static final Logger logger = Logger.getLogger(PreSerializedServer.class.getName()); |
| 47 | + |
| 48 | + private Server server; |
| 49 | + |
| 50 | + private void start() throws IOException { |
| 51 | + int port = 50051; |
| 52 | + server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create()) |
| 53 | + .addService(new GreeterImpl()) |
| 54 | + .build() |
| 55 | + .start(); |
| 56 | + logger.info("Server started, listening on " + port); |
| 57 | + Runtime.getRuntime().addShutdownHook(new Thread() { |
| 58 | + @Override |
| 59 | + public void run() { |
| 60 | + // Use stderr here since the logger may have been reset by its JVM shutdown hook. |
| 61 | + System.err.println("*** shutting down gRPC server since JVM is shutting down"); |
| 62 | + try { |
| 63 | + PreSerializedServer.this.stop(); |
| 64 | + } catch (InterruptedException e) { |
| 65 | + e.printStackTrace(System.err); |
| 66 | + } |
| 67 | + System.err.println("*** server shut down"); |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + private void stop() throws InterruptedException { |
| 73 | + if (server != null) { |
| 74 | + server.shutdown().awaitTermination(30, TimeUnit.SECONDS); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Await termination on the main thread since the grpc library uses daemon threads. |
| 80 | + */ |
| 81 | + private void blockUntilShutdown() throws InterruptedException { |
| 82 | + if (server != null) { |
| 83 | + server.awaitTermination(); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Main launches the server from the command line. |
| 89 | + */ |
| 90 | + public static void main(String[] args) throws IOException, InterruptedException { |
| 91 | + final PreSerializedServer server = new PreSerializedServer(); |
| 92 | + server.start(); |
| 93 | + server.blockUntilShutdown(); |
| 94 | + } |
| 95 | + |
| 96 | + static class GreeterImpl implements GreeterGrpc.AsyncService, BindableService { |
| 97 | + |
| 98 | + public void byteSayHello(HelloRequest req, StreamObserver<byte[]> responseObserver) { |
| 99 | + HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build(); |
| 100 | + responseObserver.onNext(reply.toByteArray()); |
| 101 | + responseObserver.onCompleted(); |
| 102 | + } |
| 103 | + |
| 104 | + @Override |
| 105 | + public ServerServiceDefinition bindService() { |
| 106 | + MethodDescriptor<HelloRequest, HelloReply> sayHello = GreeterGrpc.getSayHelloMethod(); |
| 107 | + // Modifying the method descriptor to use bytes as the response, instead of HelloReply. By |
| 108 | + // adjusting toBuilder() you can choose which of the request and response are bytes. |
| 109 | + MethodDescriptor<HelloRequest, byte[]> byteSayHello = sayHello |
| 110 | + .toBuilder(sayHello.getRequestMarshaller(), new ByteArrayMarshaller()) |
| 111 | + .build(); |
| 112 | + // GreeterGrpc.bindService() will bind every service method, including sayHello(). (Although |
| 113 | + // Greeter only has one method, this approach would work for any service.) AsyncService |
| 114 | + // provides a default implementation of sayHello() that returns UNIMPLEMENTED, and that |
| 115 | + // implementation will be used by bindService(). replaceMethod() will rewrite that method to |
| 116 | + // use our byte-based method instead. |
| 117 | + // |
| 118 | + // The generated bindService() uses ServerCalls to make RPC handlers. Since the generated |
| 119 | + // bindService() won't expect byte[] in the AsyncService, this uses ServerCalls directly. It |
| 120 | + // isn't as convenient, but it behaves the same as a normal RPC handler. |
| 121 | + return replaceMethod( |
| 122 | + GreeterGrpc.bindService(this), |
| 123 | + byteSayHello, |
| 124 | + ServerCalls.asyncUnaryCall(this::byteSayHello)); |
| 125 | + } |
| 126 | + |
| 127 | + /** Rewrites the ServerServiceDefinition replacing one method's definition. */ |
| 128 | + private static <ReqT, RespT> ServerServiceDefinition replaceMethod( |
| 129 | + ServerServiceDefinition def, |
| 130 | + MethodDescriptor<ReqT, RespT> newDesc, |
| 131 | + ServerCallHandler<ReqT, RespT> newHandler) { |
| 132 | + // There are two data structures involved. The first is the "descriptor" which describes the |
| 133 | + // service and methods as a schema. This is the same on client and server. The second is the |
| 134 | + // "definition" which includes the handlers to execute methods. This is specific to the server |
| 135 | + // and is generated by "bind." This adjusts both the descriptor and definition. |
| 136 | + |
| 137 | + // Descriptor |
| 138 | + ServiceDescriptor desc = def.getServiceDescriptor(); |
| 139 | + ServiceDescriptor.Builder descBuilder = ServiceDescriptor.newBuilder(desc.getName()) |
| 140 | + .setSchemaDescriptor(desc.getSchemaDescriptor()) |
| 141 | + .addMethod(newDesc); // Add the modified method |
| 142 | + // Copy methods other than the modified one |
| 143 | + for (MethodDescriptor<?,?> md : desc.getMethods()) { |
| 144 | + if (newDesc.getFullMethodName().equals(md.getFullMethodName())) { |
| 145 | + continue; |
| 146 | + } |
| 147 | + descBuilder.addMethod(md); |
| 148 | + } |
| 149 | + |
| 150 | + // Definition |
| 151 | + ServerServiceDefinition.Builder defBuilder = |
| 152 | + ServerServiceDefinition.builder(descBuilder.build()) |
| 153 | + .addMethod(newDesc, newHandler); // Add the modified method |
| 154 | + // Copy methods other than the modified one |
| 155 | + for (ServerMethodDefinition<?,?> smd : def.getMethods()) { |
| 156 | + if (newDesc.getFullMethodName().equals(smd.getMethodDescriptor().getFullMethodName())) { |
| 157 | + continue; |
| 158 | + } |
| 159 | + defBuilder.addMethod(smd); |
| 160 | + } |
| 161 | + return defBuilder.build(); |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments