import java.io.IOException;
import org.springframework.boot.web.server.WebServer;import org.springframework.boot.web.server.WebServerException;
import io.grpc.Server;import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
public class NettyWebServer implements WebServer{
public static final int DEFAULT_PORT = 50051; Server server; @Override public void start() throws WebServerException { if(server == null) server = NettyServerBuilder.forPort(DEFAULT_PORT).build(); try { server.start(); } catch (IOException e) { e.printStackTrace(); } 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"); NettyWebServer.this.stop(); System.err.println("*** server shut down"); } }); startDaemonAwaitThread(); }
@Override public void stop() throws WebServerException { if (server != null) { server.shutdown(); } }
@Override public int getPort() { return DEFAULT_PORT; } private void startDaemonAwaitThread() { Thread awaitThread = new Thread(()->{ try { NettyWebServer.this.server.awaitTermination(); } catch (InterruptedException e) {// log.error("gRPC server stopped.", e); } }); awaitThread.setContextClassLoader(getClass().getClassLoader()); awaitThread.setDaemon(false); awaitThread.start(); }
}@SpringBootApplicationpublic class GrpcBoot{
public static void main(String[] args) throws Exception { SpringApplication.run(GrpcBoot.class, args); }
@Bean ServletWebServerFactory servletWebServerFactory() { return new ServletWebServerFactory() { @Override public WebServer getWebServer(ServletContextInitializer... initializers) { return new NettyWebServer(); } }; } }2018-11-10 16:32:02.499 INFO 17044 --- [ main] com.omid.grpc.boot.GrpcBoot : Starting GrpcBoot on opourhadi with PID 17044 (/home/omidp/workspace-grpc/grpc-crud/grpc-server/target/classes started2018-11-10 16:32:02.502 INFO 17044 --- [ main] com.omid.grpc.boot.GrpcBoot : No active profile set, falling back to default profiles: default2018-11-10 16:32:02.534 INFO 17044 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3c9d0b9d: startup date [Sat Nov 10 16:32:02 IRST 2018]; root of context hierarchy2018-11-10 16:32:03.054 INFO 17044 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup2018-11-10 16:32:03.063 INFO 17044 --- [ main] com.omid.grpc.boot.GrpcBoot : Started GrpcBoot in 0.738 seconds (JVM running for 1.022)2018-11-10 16:32:03.065 INFO 17044 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3c9d0b9d: startup date [Sat Nov 10 16:32:02 IRST 2018]; root of context hierarchy2018-11-10 16:32:03.067 INFO 17044 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown