下面列出了怎么用io.netty.util.internal.SystemPropertyUtil的API类实例代码及写法,或者点击链接到github查看源代码。
private NettySocketSslContext() {
String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
try {
//
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(SslKeyStore.asInputStream(), SslKeyStore.getKeyStorePassword());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keystore, SslKeyStore.getCertificatePassword());
// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
}
DefaultResourceLeakDetectorFactory() {
String customLeakDetector;
try {
customLeakDetector = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return SystemPropertyUtil.get("io.netty.customResourceLeakDetector");
}
});
} catch (Throwable cause) {
logger.error("Could not access System property: io.netty.customResourceLeakDetector", cause);
customLeakDetector = null;
}
if (customLeakDetector == null) {
obsoleteCustomClassConstructor = customClassConstructor = null;
} else {
obsoleteCustomClassConstructor = obsoleteCustomClassConstructor(customLeakDetector);
customClassConstructor = customClassConstructor(customLeakDetector);
}
}
@Test
@SuppressForbidden(reason = "testing fallback to Runtime#availableProcessors")
public void testGet() {
final String availableProcessorsSystemProperty = SystemPropertyUtil.get("io.netty.availableProcessors");
try {
System.clearProperty("io.netty.availableProcessors");
final NettyRuntime.AvailableProcessorsHolder holder = new NettyRuntime.AvailableProcessorsHolder();
assertThat(holder.availableProcessors(), equalTo(Runtime.getRuntime().availableProcessors()));
} finally {
if (availableProcessorsSystemProperty != null) {
System.setProperty("io.netty.availableProcessors", availableProcessorsSystemProperty);
} else {
System.clearProperty("io.netty.availableProcessors");
}
}
}
private static void loadNativeLibrary() {
String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim();
if (!name.startsWith("mac") && !name.contains("bsd") && !name.startsWith("darwin")) {
throw new IllegalStateException("Only supported on BSD");
}
String staticLibName = "netty_transport_native_kqueue";
String sharedLibName = staticLibName + '_' + PlatformDependent.normalizedArch();
ClassLoader cl = PlatformDependent.getClassLoader(Native.class);
try {
NativeLibraryLoader.load(sharedLibName, cl);
} catch (UnsatisfiedLinkError e1) {
try {
NativeLibraryLoader.load(staticLibName, cl);
logger.debug("Failed to load {}", sharedLibName, e1);
} catch (UnsatisfiedLinkError e2) {
ThrowableUtil.addSuppressed(e1, e2);
throw e1;
}
}
}
private static void loadNativeLibrary() {
String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim();
if (!name.startsWith("linux")) {
throw new IllegalStateException("Only supported on Linux");
}
String staticLibName = "netty_transport_native_epoll";
String sharedLibName = staticLibName + '_' + PlatformDependent.normalizedArch();
ClassLoader cl = PlatformDependent.getClassLoader(Native.class);
try {
NativeLibraryLoader.load(sharedLibName, cl);
} catch (UnsatisfiedLinkError e1) {
try {
NativeLibraryLoader.load(staticLibName, cl);
logger.debug("Failed to load {}", sharedLibName, e1);
} catch (UnsatisfiedLinkError e2) {
ThrowableUtil.addSuppressed(e1, e2);
throw e1;
}
}
}
private NettySocketSslContext() {
String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
try {
//
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(SslKeyStore.asInputStream(), SslKeyStore.getKeyStorePassword());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keystore, SslKeyStore.getCertificatePassword());
// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
}
private NettySocketSslContext() {
String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
try {
//
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(SslKeyStore.asInputStream(), SslKeyStore.getKeyStorePassword());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keystore, SslKeyStore.getCertificatePassword());
// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
}
private void initSsl(InitNetty serverBean){
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() -> {});
String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
SSLContext serverContext;
try {
//
KeyStore ks = KeyStore.getInstance("JKS");
ks.load( SecureSocketSslContextFactory.class.getResourceAsStream(serverBean.getJksFile()),
serverBean.getJksStorePassword().toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks,serverBean.getJksCertificatePassword().toCharArray());
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error(
"Failed to initialize the server-side SSLContext", e);
}
SERVER_CONTEXT = serverContext;
}
@Test
public void testRecycleInSyncThread() throws Exception{
//recycle
Resource2 resource1 = Resource2.newInstance();
resource1.recycle();
//don't recycle
resource1 = Resource2.newInstance();
Resource2 temp =null;
// By default we allow one push to a Recycler for each 8th try on handles that were never recycled before.
// This should help to slowly increase the capacity of the recycler while not be too sensitive to allocation
// bursts.
int stackDefaultRatioMask = SystemPropertyUtil.getInt("io.netty.recycler.ratio", 8) - 1;
for(int i =0; i< stackDefaultRatioMask; i++){
temp = Resource2.newInstance();
temp.recycle();
Assert.assertTrue(temp != Resource2.newInstance());
}
temp = Resource2.newInstance();
temp.recycle();
Assert.assertTrue(temp == Resource2.newInstance());
}
private static String sanitizeUri(String uri) {
// Decode the path.
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
if (uri.isEmpty() || uri.charAt(0) != '/') {
return null;
}
// Convert file separators.
uri = uri.replace('/', File.separatorChar);
// Simplistic dumb security check.
// You will have to do something serious in the production environment.
if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.charAt(0) == '.'
|| uri.charAt(uri.length() - 1) == '.' || INSECURE_URI.matcher(uri).matches()) {
return null;
}
// Convert to absolute path.
return SystemPropertyUtil.get("user.dir") + File.separator + uri;
}
private static String sanitizeUri(String uri) {
// Decode the path.
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
if (uri.isEmpty() || uri.charAt(0) != '/') {
return null;
}
// Convert file separators.
uri = uri.replace('/', File.separatorChar);
// Simplistic dumb security check.
// You will have to do something serious in the production environment.
if (uri.contains(File.separator + '.') ||
uri.contains('.' + File.separator) ||
uri.charAt(0) == '.' || uri.charAt(uri.length() - 1) == '.' ||
INSECURE_URI.matcher(uri).matches()) {
return null;
}
// Convert to absolute path.
return SystemPropertyUtil.get("user.dir") + File.separator + uri;
}
@Test
public void testGetWithSystemProperty() {
final String availableProcessorsSystemProperty = SystemPropertyUtil.get("io.netty.availableProcessors");
try {
System.setProperty("io.netty.availableProcessors", "2048");
final NettyRuntime.AvailableProcessorsHolder holder = new NettyRuntime.AvailableProcessorsHolder();
assertThat(holder.availableProcessors(), equalTo(2048));
} finally {
if (availableProcessorsSystemProperty != null) {
System.setProperty("io.netty.availableProcessors", availableProcessorsSystemProperty);
} else {
System.clearProperty("io.netty.availableProcessors");
}
}
}
private static boolean useEpoll() {
// Should we just return true if this is Linux and if we get an error
// during Epoll
// setup handle it there?
final String os = SystemPropertyUtil.get(OS_NAME).toLowerCase().trim();
final String[] version = SystemPropertyUtil.get(OS_VERSION).toLowerCase().trim().split("\\.");
if (os.startsWith("linux") && version.length >= 3) {
final int major = Integer.parseInt(version[0]);
if (major > EPOLL_MIN_MAJOR_VERSION) {
return true;
} else if (major == EPOLL_MIN_MAJOR_VERSION) {
final int minor = Integer.parseInt(version[1]);
if (minor > EPOLL_MIN_MINOR_VERSION) {
return true;
} else if (minor == EPOLL_MIN_MINOR_VERSION) {
final int patch = Integer.parseInt(version[2].substring(0, 2));
return patch >= EPOLL_MIN_PATCH_VERSION;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private static boolean useEpoll() {
// Should we just return true if this is Linux and if we get an error
// during Epoll
// setup handle it there?
final String os = SystemPropertyUtil.get(OS_NAME).toLowerCase().trim();
final String[] version = SystemPropertyUtil.get(OS_VERSION).toLowerCase().trim().split("\\.");
if (os.startsWith("linux") && version.length >= 3) {
final int major = Integer.parseInt(version[0]);
if (major > EPOLL_MIN_MAJOR_VERSION) {
return true;
} else if (major == EPOLL_MIN_MAJOR_VERSION) {
final int minor = Integer.parseInt(version[1]);
if (minor > EPOLL_MIN_MINOR_VERSION) {
return true;
} else if (minor == EPOLL_MIN_MINOR_VERSION) {
final int patch = Integer.parseInt(version[2].substring(0, 2));
return patch >= EPOLL_MIN_PATCH_VERSION;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private static boolean useEpoll() {
// Should we just return true if this is Linux and if we get an error
// during Epoll
// setup handle it there?
final String os = SystemPropertyUtil.get(OS_NAME).toLowerCase().trim();
final String[] version = SystemPropertyUtil.get(OS_VERSION).toLowerCase().trim().split("\\.");
if (os.startsWith("linux") && version.length >= 3) {
final int major = Integer.parseInt(version[0]);
if (major > EPOLL_MIN_MAJOR_VERSION) {
return true;
} else if (major == EPOLL_MIN_MAJOR_VERSION) {
final int minor = Integer.parseInt(version[1]);
if (minor > EPOLL_MIN_MINOR_VERSION) {
return true;
} else if (minor == EPOLL_MIN_MINOR_VERSION) {
final int patch = Integer.parseInt(version[2].substring(0, 2));
return patch >= EPOLL_MIN_PATCH_VERSION;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private static boolean useEpoll() {
// Should we just return true if this is Linux and if we get an error
// during Epoll
// setup handle it there?
final String os = SystemPropertyUtil.get(OS_NAME).toLowerCase().trim();
final String[] version = SystemPropertyUtil.get(OS_VERSION).toLowerCase().trim().split("\\.");
if (os.startsWith("linux") && version.length >= 3) {
final int major = Integer.parseInt(version[0]);
if (major > EPOLL_MIN_MAJOR_VERSION) {
return true;
} else if (major == EPOLL_MIN_MAJOR_VERSION) {
final int minor = Integer.parseInt(version[1]);
if (minor > EPOLL_MIN_MINOR_VERSION) {
return true;
} else if (minor == EPOLL_MIN_MINOR_VERSION) {
final int patch = Integer.parseInt(version[2].substring(0, 2));
return patch >= EPOLL_MIN_PATCH_VERSION;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private static String sanitizeUri(String uri) {
// Decode the path.
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
if (uri.isEmpty() || uri.charAt(0) != '/') {
return null;
}
// Convert file separators.
uri = uri.replace('/', File.separatorChar);
// Simplistic dumb security check.
// You will have to do something serious in the production environment.
if (uri.contains(File.separator + '.') ||
uri.contains('.' + File.separator) ||
uri.charAt(0) == '.' || uri.charAt(uri.length() - 1) == '.' ||
INSECURE_URI.matcher(uri).matches()) {
return null;
}
// Convert to absolute path.
return SystemPropertyUtil.get("user.dir") + File.separator + uri;
}
private static void disableNettyLeakDetector() {
String leakProperty = SystemPropertyUtil.get("io.netty.leakDetection.level");
//we do not pass any with JVM option
if (leakProperty == null) {
System.setProperty("io.netty.leakDetection.level", "disabled");
}
}
@VisibleForTesting
static void init()
{
// We should always prefer direct buffers by default if Netty prefers it and not explicitly prohibited.
DIRECT_BUFFER_PREFERRED = PlatformDependent.directBufferPreferred()
&& !SystemPropertyUtil.getBoolean("com.uber.tchannel.thrift_serializer.noPreferDirect", false);
if (logger.isDebugEnabled()) {
logger.debug("-Dcom.uber.tchannel.thrift_serializer.noPreferDirect: {}", !DIRECT_BUFFER_PREFERRED);
}
}
private static String sanitizeUri(String uri) {
// Decode the path.
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
if (uri.isEmpty() || uri.charAt(0) != '/') {
return null;
}
// Convert file separators.
uri = uri.replace('/', File.separatorChar);
// Simplistic dumb security check.
// You will have to do something serious in the production environment.
if (uri.contains(File.separator + '.') ||
uri.contains('.' + File.separator) ||
uri.charAt(0) == '.' || uri.charAt(uri.length() - 1) == '.' ||
INSECURE_URI.matcher(uri).matches()) {
return null;
}
// Convert to absolute path.
return SystemPropertyUtil.get("user.dir") + File.separator + uri;
}
protected int getForks() {
return SystemPropertyUtil.getInt("forks", -1);
}
protected int getWarmupIterations() {
return SystemPropertyUtil.getInt("warmupIterations", -1);
}
protected int getMeasureIterations() {
return SystemPropertyUtil.getInt("measureIterations", -1);
}
protected String getReportDir() {
return SystemPropertyUtil.get("perfReportDir");
}
@Override
public Boolean run() {
return SystemPropertyUtil.getBoolean(
"io.netty.handler.ssl.openssl.useKeyManagerFactory", true);
}
@Override
public Integer run() {
return Math.max(1,
SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.bioNonApplicationBufferSize",
2048));
}
@Override
public String run() {
return SystemPropertyUtil.get("jdk.tls.ephemeralDHKeySize");
}
public AbstractServer(String id, String groupName, String serverName, int port, ServerConfig config) {
this.group = groupName;
InetTools inetTools = new InetTools();
InetAddress firstNonLoopbackAddress = inetTools.findFirstNonLoopbackAddress();
inetTools.close();
// this.address = getLocalHostLANAddress();
this.address = firstNonLoopbackAddress;
this.id = id == null ? group + "@" + address.getHostName() + ":" + port : id;
this.startTimestamp = System.currentTimeMillis();
this.version = CoreVersion.getVersion();
this.serverName = serverName;
this.port = port;
this.config = config;
serverStateRef = new AtomicReference<>(ServerState.Created);
int bossThreads = ObjectUtils.defaultIfNull(config.getBoss(), 1);
int defaultWorks = Math.max(1, SystemPropertyUtil.getInt(
"io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
int workThreads = ObjectUtils.defaultIfNull(config.getWorker(), defaultWorks);
boss = useEpoll() ? new EpollEventLoopGroup(bossThreads) : new NioEventLoopGroup(bossThreads);
worker = useEpoll() ? new EpollEventLoopGroup(workThreads) : new NioEventLoopGroup(workThreads);
bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker).channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
// 启用Pool Bytebuf,http request的content将使用堆外pooled direct bytebuf,其它信息(header)仍然是堆内
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.SO_BACKLOG, config.soBacklog)
.childOption(ChannelOption.SO_KEEPALIVE, config.soKeepAlive)
.childOption(ChannelOption.TCP_NODELAY, config.tcpNoDelay)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_RCVBUF, 24 * 1024)
.childOption(ChannelOption.SO_SNDBUF, 24 * 1024)
//ChannelOut boundBuffer 高水位线 低水位线
.option(ChannelOption.WRITE_BUFFER_WATER_MARK, WriteBufferWaterMark.DEFAULT)
.handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(newChannelInitializer());
}
public Server(Configuration conf) throws Exception {
DEFAULT_EVENT_LOOP_THREADS = Math.max(1,
SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
this.config = conf;
}
protected int getWarmupIterations() {
return SystemPropertyUtil.getInt("warmupIterations", -1);
}