基于netty的tcp框架搭建-根据操作系统启动不同netty服务
根据操作系统启动不同netty服务
netty在linux上提供了epoll模式的支持,性能提高显著,
针对netty的原理将会在之后的文章里整理,
epoll仅linux支持,windows不支持,这对于开发和部署就很尴尬了,需要各种切换。
如果能自动识别操作系统,不就可以偷个小懒,岂不美哉。
代码
项目框架使用的是springboot,
在框架中启动netty服务
package com.commuli.tcp.netty.init;
import com.commuli.core.common.utils.OSUtil;
import com.commuli.tcp.netty.server.NettyEpollServer;
import com.commuli.tcp.netty.server.NettyNioServer;
import com.commuli.tcp.netty.server.NettyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author commuli
* @date 2019/4/25
*/
@Component
@Order(3)
public class InitServer implements ApplicationRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(InitServer.class);
@Override
public void run(ApplicationArguments args) throws Exception {
Thread thread = new Thread(() -> {
//启动netty项目
//获取操作系统类型,更具类型启动不同的netty
NettyServer server = null;
if (OSUtil.isWindows()) {
server = new NettyNioServer();
} else if (OSUtil.isLinux()) {
server = new NettyEpollServer();
}
if (server != null) {
try {
server.start();
} catch (Exception e) {
LOGGER.error("启动netty异常:{}", e);
System.exit(0);
}
}
});
thread.setName("netty-server-thread");
thread.start();
}
}
操作系统工具类,识别操作系统类型
package com.commuli.core.common.utils;
/**
* @author commuli
* @date 2019/4/24
*/
public class OSUtil {
private static final String OS = System.getProperty("os.name").toLowerCase();
public static boolean isLinux() {
return OS.indexOf("linux") >= 0;
}
public static boolean isMacOS() {
return OS.indexOf("mac") >= 0 && OS.indexOf("os") > 0 && OS.indexOf("x") < 0;
}
public static boolean isMacOSX() {
return OS.indexOf("mac") >= 0 && OS.indexOf("os") > 0 && OS.indexOf("x") > 0;
}
public static boolean isWindows() {
return OS.indexOf("windows") >= 0;
}
}