1. Load ssl certificates Tools
public class SslUtil { Private static volatile the SSLContext SSLContext = null ; public static the SSLContext createSSLContext (type String, String path, String password) throws Exception { IF ( null == SSLContext) { the synchronized (. SslUtil class ) { IF ( null == SSLContext ) { // support JKS, PKCS12 ( our project with a certificate Ali cloud free application, download pfx file after decompression tomcat, corresponding to the PKCS12 ) KeyStore KS = KeyStore.getInstance(type); // 证书存放地址 InputStream ksInputStream = new FileInputStream(path); ks.load(ksInputStream, password.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password.toCharArray()); sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), null, null); } } } return sslContext; } }
2. SslHandler placed in the first
bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // SSL处理器 SSLContext sslContext = SslUtil.createSSLContext(BaseGlobal.getCertType(), BaseGlobal.getCertPath(), BaseGlobal.getCertPassword()); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setNeedClientAuth(false); sslEngine.setUseClientMode(false); pipeline.addLast("sslHandler", new SslHandler(sslEngine)); pipeline.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)); ... } });
3. Because of the special nature of our project, but also supports TCP, WS protocol, the use of multiple threads to load two NettyServer
@EnableCaching @EnableAutoConfiguration @SpringBootApplication (scanBasePackages = "XXX" ) @MapperScan (basePackages = "XXX" ) @EnableAsync public class V3xboxApplication { public static void main (String [] args) { SpringApplication.run (V3xboxApplication. Class , args); // start the server (client TCP connection) // use thread starts, because Netty's sync method blocks thread // here reason not to use the thread pool is here only one thread, the thread does not exist frequent destruction of creation = new new nettyServerThread nettyServerThread nettyServerThread (); the Thread = new new Thread1 the Thread (nettyServerThread); thread1.start (); // if port case provided wss, wss processing server is started IF (StringUtil.isNotEmpty (BaseGlobal.getWssPort ())) { NettyWssServerThread sslServerThread new new NettyWssServerThread = (); the Thread = new new Thread2 the Thread (sslServerThread); thread2.start (); } } }
4. Because we need to dynamically determine WS or WSS in the program, so the nginx proxy configuration, so the background can be identified client is http or https
proxy_set_header scheme $scheme;
Reference: https://www.cnblogs.com/qingyibusi/p/8572783.html