代码优化

This commit is contained in:
aoshiguchen
2022-08-30 10:29:37 +08:00
parent 54e968438a
commit 9bfa5de353
15 changed files with 165 additions and 180 deletions
@@ -22,14 +22,12 @@
package fun.asgc.neutrino.proxy.client.core;
import com.alibaba.fastjson.JSONObject;
import fun.asgc.neutrino.core.annotation.Autowired;
import fun.asgc.neutrino.core.annotation.Bean;
import fun.asgc.neutrino.core.annotation.Component;
import fun.asgc.neutrino.core.annotation.NonIntercept;
import fun.asgc.neutrino.core.context.ApplicationRunner;
import fun.asgc.neutrino.core.util.ArrayUtil;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.FileUtil;
import fun.asgc.neutrino.core.util.StringUtil;
import fun.asgc.neutrino.proxy.client.config.ProxyConfig;
@@ -160,30 +158,6 @@ public class ProxyClientRunner implements ApplicationRunner {
return new Bootstrap();
}
private ProxyClientConfig getClientConfig(String path) {
if (StringUtil.isEmpty(path)) {
path = "./config.json";
}
String content = FileUtil.readContentAsString(path);
if (StringUtil.isEmpty(content)) {
log.error("配置文件: {} 不存在或格式异常!", path);
System.exit(0);
return null;
}
try {
ProxyClientConfig clientConfig = JSONObject.parseObject(content, ProxyClientConfig.class);
if (StringUtil.isEmpty(clientConfig.getClientKey()) || CollectionUtil.isEmpty(clientConfig.getProxy())) {
log.error("配置异常!");
System.exit(0);
return null;
}
return clientConfig;
} catch (Exception e) {
log.error("解析配置文件异常!", e);
}
return null;
}
private String getLicenseKey(String[] args) {
String license = "";
if (null != args && ArrayUtil.notEmpty(args)) {
@@ -38,8 +38,6 @@ import java.util.Map;
public class ProxyConfig {
private Protocol protocol;
private Server server;
@Value("license")
private Map<String, Integer> licenseMap;
@Data
public static class Protocol {
@@ -1,126 +0,0 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fun.asgc.neutrino.proxy.server.base.proxy;
import fun.asgc.neutrino.proxy.core.ProxyClientConfig;
import fun.asgc.neutrino.proxy.server.dal.entity.PortMappingDO;
import lombok.Data;
import java.io.Serializable;
import java.util.*;
/**
*
* @author: aoshiguchen
* @date: 2022/6/16
*/
public class ProxyServerConfig implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 更新配置后保证在其他线程即时生效
*/
private static ProxyServerConfig instance = new ProxyServerConfig();;
/**
* 代理服务器为各个代理客户端(key)开启对应的端口列表(value)
*/
private volatile Map<String, List<Integer>> clientInetPortMapping = new HashMap<String, List<Integer>>();
/**
* 代理服务器上的每个对外端口(key)对应的代理客户端背后的真实服务器信息(value)
*/
private volatile Map<Integer, String> inetPortLanInfoMapping = new HashMap<Integer, String>();
public void addClientConfig(String licenseKey, List<PortMappingDO> portMappingList) {
String clientKey = licenseKey;
List<Integer> ports = new ArrayList<>();
for (PortMappingDO portMapping : portMappingList) {
ports.add(portMapping.getServerPort());
inetPortLanInfoMapping.put(portMapping.getServerPort(), portMapping.getClientIp() + ":" + portMapping.getClientPort());
}
clientInetPortMapping.put(clientKey, ports);
}
/**
* 获取代理客户端对应的代理服务器端口
*
* @param clientKey
* @return
*/
public List<Integer> getClientInetPorts(String clientKey) {
return clientInetPortMapping.get(clientKey);
}
/**
* 根据代理服务器端口获取后端服务器代理信息
*
* @param port
* @return
*/
public String getLanInfo(Integer port) {
return inetPortLanInfoMapping.get(port);
}
/**
* 返回需要绑定在代理服务器的端口(用于用户请求)
*
* @return
*/
public List<Integer> getUserPorts() {
List<Integer> ports = new ArrayList<Integer>();
Iterator<Integer> ite = inetPortLanInfoMapping.keySet().iterator();
while (ite.hasNext()) {
ports.add(ite.next());
}
return ports;
}
public static ProxyServerConfig getInstance() {
return instance;
}
/**
* 代理客户端与其后面真实服务器映射关系
*
* @author fengfei
*
*/
@Data
public static class ClientProxyMapping {
/**
* 代理服务器端口
*/
private Integer inetPort;
/**
* 需要代理的网络信息(代理客户端能够访问),格式 192.168.1.99:80 (必须带端口)
*/
private String lan;
}
}
@@ -54,11 +54,13 @@ public class VisitLogInterceptor implements HandlerInterceptor {
Date receiveTime = SystemContextHolder.getContext().getReceiveTime();
Date now = new Date();
long elapsedTime = now.getTime() - receiveTime.getTime();
log.info("\n-----------------------------------------------------------------接口请求日志:\n{} url:{} 执行耗时:{}\nURL参数:{}\n请求体参数:{}\n响应结果:{}",
log.info("\n-----------------------------------------------------------------接口请求日志:\n{} url:{} 执行耗时:{}\nURL参数:{}\n请求体参数:{}\n响应结果:{}\n客户端IP:{}\n",
requestParser.getMethod().name(), requestParser.getUrl(), getElapsedTimeStr(elapsedTime),
requestParser.getQueryString(),
requestParser.getContentAsString(),
JSONObject.toJSONString(result));
JSONObject.toJSONString(result),
SystemContextHolder.getIp()
);
}
/**
@@ -23,10 +23,7 @@ package fun.asgc.neutrino.proxy.server.controller;
import fun.asgc.neutrino.core.annotation.Autowired;
import fun.asgc.neutrino.core.annotation.NonIntercept;
import fun.asgc.neutrino.core.web.annotation.PostMapping;
import fun.asgc.neutrino.core.web.annotation.RequestBody;
import fun.asgc.neutrino.core.web.annotation.RequestMapping;
import fun.asgc.neutrino.core.web.annotation.RestController;
import fun.asgc.neutrino.core.web.annotation.*;
import fun.asgc.neutrino.proxy.server.base.rest.Authorization;
import fun.asgc.neutrino.proxy.server.controller.req.LoginReq;
import fun.asgc.neutrino.proxy.server.controller.res.LoginRes;
@@ -58,5 +55,4 @@ public class IndexController {
public void logout() {
userService.logout();
}
}
@@ -22,7 +22,7 @@
package fun.asgc.neutrino.proxy.server.proxy.core;
import fun.asgc.neutrino.proxy.server.proxy.monitor.MetricsCollector;
import fun.asgc.neutrino.proxy.server.proxy.domain.MetricsCollector;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
@@ -24,8 +24,8 @@ package fun.asgc.neutrino.proxy.server.proxy.core;
import fun.asgc.neutrino.proxy.core.Constants;
import fun.asgc.neutrino.proxy.core.ProxyMessage;
import fun.asgc.neutrino.proxy.server.base.proxy.ProxyServerConfig;
import fun.asgc.neutrino.proxy.server.util.ProxyChannelManager;
import fun.asgc.neutrino.proxy.server.util.ProxyUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
@@ -80,7 +80,7 @@ public class UserChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {
ctx.channel().close();
} else {
String userId = newUserId();
String lanInfo = ProxyServerConfig.getInstance().getLanInfo(sa.getPort());
String lanInfo = ProxyUtil.getClientLanInfoByServerPort(sa.getPort());
// 用户连接到代理服务器时,设置用户连接不可读,等待代理后端服务器连接成功后再改变为可读状态
userChannel.config().setOption(ChannelOption.AUTO_READ, false);
ProxyChannelManager.addUserChannelToCmdChannel(cmdChannel, userId, userChannel);
@@ -20,7 +20,7 @@
* SOFTWARE.
*/
package fun.asgc.neutrino.proxy.server.proxy.monitor;
package fun.asgc.neutrino.proxy.server.proxy.domain;
import lombok.Data;
@@ -20,7 +20,7 @@
* SOFTWARE.
*/
package fun.asgc.neutrino.proxy.server.proxy.monitor;
package fun.asgc.neutrino.proxy.server.proxy.domain;
import java.util.ArrayList;
import java.util.Iterator;
@@ -0,0 +1,62 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fun.asgc.neutrino.proxy.server.proxy.domain;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.proxy.server.dal.entity.PortMappingDO;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author: aoshiguchen
* @date: 2022/8/30
*/
@Accessors(chain = true)
@Data
public class ProxyMapping {
/**
* 服务端端口
*/
private Integer serverPort;
/**
* 客户端信息 IP:port
*/
private String lanInfo;
public static List<ProxyMapping> buildList(List<PortMappingDO> portMappingList) {
List<ProxyMapping> list = new ArrayList<>();
if (CollectionUtil.isEmpty(portMappingList)) {
return list;
}
for (PortMappingDO portMapping : portMappingList) {
list.add(new ProxyMapping()
.setServerPort(portMapping.getServerPort())
.setLanInfo(String.format("%s:%s", portMapping.getClientIp(), portMapping.getClientPort())));
}
return list;
}
}
@@ -30,17 +30,18 @@ import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.StringUtil;
import fun.asgc.neutrino.proxy.core.*;
import fun.asgc.neutrino.proxy.server.base.proxy.ProxyConfig;
import fun.asgc.neutrino.proxy.server.base.proxy.ProxyServerConfig;
import fun.asgc.neutrino.proxy.server.base.rest.constant.EnableStatusEnum;
import fun.asgc.neutrino.proxy.server.proxy.core.BytesMetricsHandler;
import fun.asgc.neutrino.proxy.server.proxy.core.UserChannelHandler;
import fun.asgc.neutrino.proxy.server.dal.entity.LicenseDO;
import fun.asgc.neutrino.proxy.server.dal.entity.PortMappingDO;
import fun.asgc.neutrino.proxy.server.dal.entity.UserDO;
import fun.asgc.neutrino.proxy.server.proxy.domain.ProxyMapping;
import fun.asgc.neutrino.proxy.server.service.LicenseService;
import fun.asgc.neutrino.proxy.server.service.PortMappingService;
import fun.asgc.neutrino.proxy.server.service.UserService;
import fun.asgc.neutrino.proxy.server.util.ProxyChannelManager;
import fun.asgc.neutrino.proxy.server.util.ProxyUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
@@ -52,6 +53,7 @@ import lombok.extern.slf4j.Slf4j;
import java.net.BindException;
import java.util.List;
import java.util.Set;
/**
*
@@ -108,8 +110,8 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
return;
}
ProxyServerConfig.getInstance().addClientConfig(licenseKey, portMappingList);
List<Integer> ports = ProxyServerConfig.getInstance().getClientInetPorts(licenseKey);
ProxyUtil.initProxyInfo(licenseKey, ProxyMapping.buildList(portMappingList));
Set<Integer> ports = ProxyUtil.getServerPortsByLicenseKey(licenseKey);
if (ports == null) {
ctx.channel().close();
return;
@@ -131,7 +133,7 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
return ProxyDataTypeEnum.AUTH.getDesc();
}
private void startUserPortServer(List<Integer> ports) {
private void startUserPortServer(Set<Integer> ports) {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(serverBossGroup, serverWorkerGroup)
.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@@ -39,7 +39,7 @@ public class HttpUtil {
* 获取客户端IP
*/
public static String getIP(ChannelHandlerContext context, HttpRequestWrapper request) {
String ip = request.getHeaderValue("clientip"); // for UC browser
String ip = request.getHeaderValue("clientip");
if (ip == null) {
ip = request.getHeaderValue("X-Real-IP");
if (ip == null) {
@@ -23,14 +23,13 @@
package fun.asgc.neutrino.proxy.server.util;
import fun.asgc.neutrino.proxy.core.Constants;
import fun.asgc.neutrino.proxy.server.base.proxy.ProxyServerConfig;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
@@ -44,7 +43,7 @@ public class ProxyChannelManager {
private static final AttributeKey<String> REQUEST_LAN_INFO = AttributeKey.newInstance("request_lan_info");
private static final AttributeKey<List<Integer>> CHANNEL_PORT = AttributeKey.newInstance("channel_port");
private static final AttributeKey<Set<Integer>> CHANNEL_PORT = AttributeKey.newInstance("channel_port");
private static final AttributeKey<String> CHANNEL_CLIENT_KEY = AttributeKey.newInstance("channel_client_key");
@@ -58,7 +57,7 @@ public class ProxyChannelManager {
* @param ports
* @param channel
*/
public static void addCmdChannel(List<Integer> ports, String clientKey, Channel channel) {
public static void addCmdChannel(Set<Integer> ports, String clientKey, Channel channel) {
if (ports == null) {
throw new IllegalArgumentException("port can not be null");
}
@@ -93,7 +92,7 @@ public class ProxyChannelManager {
cmdChannels.put(clientKey, channel);
}
List<Integer> ports = channel.attr(CHANNEL_PORT).get();
Set<Integer> ports = channel.attr(CHANNEL_PORT).get();
for (int port : ports) {
Channel proxyChannel = portCmdChannelMapping.remove(port);
if (proxyChannel == null) {
@@ -136,7 +135,7 @@ public class ProxyChannelManager {
*/
public static void addUserChannelToCmdChannel(Channel cmdChannel, String userId, Channel userChannel) {
InetSocketAddress sa = (InetSocketAddress) userChannel.localAddress();
String lanInfo = ProxyServerConfig.getInstance().getLanInfo(sa.getPort());
String lanInfo = ProxyUtil.getClientLanInfoByServerPort(sa.getPort());
userChannel.attr(Constants.USER_ID).set(userId);
userChannel.attr(REQUEST_LAN_INFO).set(lanInfo);
cmdChannel.attr(USER_CHANNELS).get().put(userId, userChannel);
@@ -0,0 +1,81 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fun.asgc.neutrino.proxy.server.util;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.StringUtil;
import fun.asgc.neutrino.proxy.server.proxy.domain.ProxyMapping;
import java.util.*;
/**
*
* @author: aoshiguchen
* @date: 2022/8/30
*/
public class ProxyUtil {
/**
* license -> 服务端口映射
*/
private static final Map<String, Set<Integer>> licenseToServerPortMap = new HashMap<>();
/**
* 代理信息映射
*/
private static final Map<Integer, String> proxyInfoMap = new HashMap<>();
/**
* 初始化代理信息
* @param licenseKey 客户端licenseKey
* @param proxyMappingList 代理映射集合
*/
public static void initProxyInfo(String licenseKey, List<ProxyMapping> proxyMappingList) {
if (StringUtil.isEmpty(licenseKey)) {
return;
}
licenseToServerPortMap.put(licenseKey, new HashSet<>());
if (CollectionUtil.isEmpty(proxyMappingList)) {
return;
}
for (ProxyMapping proxyMapping : proxyMappingList) {
licenseToServerPortMap.get(licenseKey).add(proxyMapping.getServerPort());
proxyInfoMap.put(proxyMapping.getServerPort(), proxyMapping.getLanInfo());
}
}
/**
* 根据licenseKey获取服务端端口集合
* @param licenseKey 客户端licenseKey
* @return 服务端端口集合
*/
public static Set<Integer> getServerPortsByLicenseKey(String licenseKey) {
return licenseToServerPortMap.get(licenseKey);
}
/**
* 根据服务端端口获取客户端代理信息
* @param serverPort 服务端端口
* @return 客户端代理信息
*/
public static String getClientLanInfoByServerPort(Integer serverPort) {
return proxyInfoMap.get(serverPort);
}
}
@@ -26,9 +26,6 @@ neutrino:
key-store-password: 123456
key-manager-password: 123456
jks-path: classpath:/test.jks
license:
79419a1a8691413aa5e845b9e3e90051: 3
9352b1c25f564c81a5677131d7769876: 2
data:
sqlite:
url: jdbc:sqlite:data.db