行业知识
mTLS: Netty单向/双向TLS Demo完整代码
2026-10-31 18:00:14
来源:互联网转载
NettyHelper.java: 主要用是创建EventLoopGroup和判断是否支持Epoll。
()package org.example.netty;import io.netty.channel.EventLoopGroup;import io.netty.channel.epoll.Epoll;import io.netty.channel.epoll.EpollEventLoopGroup;import io.netty.channel.epoll.EpollSocketChannel;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.http2.Http2SecurityUtil;import io.netty.handler.ssl.*;import io.netty.handler.ssl.util.InsecureTrustManagerFactory;import io.netty.handler.ssl.util.SelfSignedCertificate;import io.netty.util.concurrent.DefaultThreadFactory;import javax.net.ssl.SSLException;import java.security.cert.CertificateException;import java.util.concurrent.ThreadFactory;public class NettyHelper { static final String NETTY_EPOLL_ENABLE_KEY = "netty.epoll.enable"; static final String OS_NAME_KEY = "os.name"; static final String OS_LINUX_PREFIX = "linux"; public static EventLoopGroup eventLoopGroup(int threads, String threadFactoryName) { ThreadFactory threadFactory = new DefaultThreadFactory(threadFactoryName, true); return shouldEpoll() ? new EpollEventLoopGroup(threads, threadFactory) : new NioEventLoopGroup(threads, threadFactory); } public static boolean shouldEpoll() { if (Boolean.parseBoolean(System.getProperty(NETTY_EPOLL_ENABLE_KEY, "false"))) { String osName = System.getProperty(OS_NAME_KEY); return osName.toLowerCase().contains(OS_LINUX_PREFIX) && Epoll.isAvailable(); } return false; } public static Class