fly 2 年之前
父節點
當前提交
d82777f2b6
共有 3 個文件被更改,包括 90 次插入55 次删除
  1. 80 48
      src/Plugin/ServerListPlugin.cs
  2. 8 5
      src/WingServer.cs
  3. 2 2
      src/appsettings.json

+ 80 - 48
src/Plugin/ServerListPlugin.cs

@@ -17,6 +17,8 @@ using WingInterfaceLibrary.Enum;
 using WingInterfaceLibrary.Interface;
 using WingInterfaceLibrary.Request.Authentication;
 using WingInterfaceLibrary.Result.Device;
+using WingServerCommon.Config;
+using WingServerCommon.Config.Parameters;
 using WingServerCommon.Interfaces.Cache;
 using WingServerCommon.Log;
 using WingServerCommon.Service;
@@ -41,6 +43,8 @@ namespace WingCloudServer.Plugin
         protected IAuthenticationService _authenticationService;
         private string _apiName = string.Empty;
 
+        private string _ipLocationServiceUrl = ConfigurationManager.GetParammeter<StringParameter>("FastServer", "IpLocationServiceUrl").Value;
+
         /// <summary>
         /// 初始化
         /// </summary>
@@ -74,6 +78,10 @@ namespace WingCloudServer.Plugin
         {
             try
             {
+                if (_apiName != "IVinnoServerService/GetServerInfoListAsync")
+                {
+                    return new PluginProcessResult(responseData, false);
+                }
                 var ipAddress = context.RemoteEndPoint?.Address.ToString();
                 var ipLongAddress = IpToLong(ipAddress);
                 var serverInformationList = CacheMaintenance.Instance.Get<IDistributedServerInfosManager>()
@@ -81,12 +89,16 @@ namespace WingCloudServer.Plugin
                 var fasterServerInfo = new ServerInfoDTO();
                 var parallelOption = new ParallelOptions() { MaxDegreeOfParallelism = 4 };
                 //本地IP段检索
-                Parallel.ForEach(serverInformationList, parallelOption, (item, parallelLoopState) => {
-                    if (item.AssignClientIPList != null && item.AssignClientIPList.Any()) {
+                Parallel.ForEach(serverInformationList, parallelOption, (item, parallelLoopState) =>
+                {
+                    if (item.AssignClientIPList != null && item.AssignClientIPList.Any())
+                    {
                         var ipInfo = item.AssignClientIPList.Find(c => c.LongStartIP >= ipLongAddress && c.LongEndIP <= ipLongAddress);
-                        if (ipInfo != null && !string.IsNullOrEmpty(ipInfo.StartIp)) {
+                        if (ipInfo != null && !string.IsNullOrEmpty(ipInfo.StartIp))
+                        {
                             //本地库找到此IP
-                            fasterServerInfo = new ServerInfoDTO() {
+                            fasterServerInfo = new ServerInfoDTO()
+                            {
                                 Name = item.Name,
                                 Host = item.ServerUrl
                             };
@@ -96,63 +108,81 @@ namespace WingCloudServer.Plugin
                     }
                 });
                 List<ServerInfoDTO> list = new List<ServerInfoDTO>();
-                if (fasterServerInfo != null && !string.IsNullOrEmpty(fasterServerInfo.Name)) {
+                if (fasterServerInfo != null && !string.IsNullOrEmpty(fasterServerInfo.Name))
+                {
                     //找到,直接返回
                     list.Add(fasterServerInfo);
                     //添加其他服务器
-                    var otherServerList = serverInformationList.FindAll(c => c.Name != fasterServerInfo.Name).Select(c => new ServerInfoDTO() {
+                    var otherServerList = serverInformationList.FindAll(c => c.Name != fasterServerInfo.Name).Select(c => new ServerInfoDTO()
+                    {
                         Name = c.Name,
                         Host = c.ServerUrl,
                     }).ToList();
                     list.AddRange(otherServerList);
                 }
-                else {
+                else
+                {
                     //没找到,定位,计算,更新,返回
                     var locationInfo = GetIpLocationInfo(ipAddress);
-                    if (locationInfo.ad_info != null && !string.IsNullOrEmpty(locationInfo.ad_info.nation)) {
-                        if (locationInfo.ad_info.nation == "中国") {
+                    if (locationInfo.ad_info != null && !string.IsNullOrEmpty(locationInfo.ad_info.nation))
+                    {
+                        if (locationInfo.ad_info.nation == "中国")
+                        {
                             //最快指向北京,
-                            var fastServerInfo = serverInformationList.FindAll(c => c.Name.Contains("北京") || c.Name.Contains("BJ"))?.Select(c => new ServerInfoDTO() {
+                            var fastServerInfo = serverInformationList.FindAll(c => c.Name.Contains("北京") || c.Name.Contains("BJ"))?.Select(c => new ServerInfoDTO()
+                            {
                                 Name = c.Name,
                                 Host = c.ServerUrl,
                             })?.FirstOrDefault() ?? new ServerInfoDTO();
                             list.Add(fastServerInfo);
                             //添加其他服务器
-                            var otherServerList = serverInformationList.FindAll(c => c.Name != fastServerInfo.Name).Select(c => new ServerInfoDTO() {
+                            var otherServerList = serverInformationList.FindAll(c => c.Name != fastServerInfo.Name).Select(c => new ServerInfoDTO()
+                            {
                                 Name = c.Name,
                                 Host = c.ServerUrl,
                             }).ToList();
                             list.AddRange(otherServerList);
                         }
-                        else 
+                        else
                         {
                             var extendList = new List<ServerInfoExtend>();
-                            foreach(var item in serverInformationList) {
+                            foreach (var item in serverInformationList)
+                            {
                                 //计算最短距离
-                                // double beelineDistanceTemp = GetDistance(locationInfo.location.lat, locationInfo.location.lng, item.lat, item.lng);
-                                // var extendInfo = new ServerInfoExtend() {
-                                //     Name = item.Name,
-                                //     Host = item.ServerUrl,
-                                //     BeelineDistance = beelineDistanceTemp
-                                // };
-                                // extendList.Add(extendInfo);
+                                double beelineDistanceTemp = GetDistance(locationInfo.location.lat, locationInfo.location.lng, Convert.ToDouble(item.Lat), Convert.ToDouble(item.Lng));
+                                var extendInfo = new ServerInfoExtend()
+                                {
+                                    Name = item.Name,
+                                    Host = item.ServerUrl,
+                                    BeelineDistance = beelineDistanceTemp
+                                };
+                                extendList.Add(extendInfo);
                             }
-                            list = extendList.OrderBy(c => c.BeelineDistance).Select(e => new ServerInfoDTO() {
+                            list = extendList.OrderBy(c => c.BeelineDistance).Select(e => new ServerInfoDTO()
+                            {
                                 Name = e.Name,
                                 Host = e.Host,
                             }).ToList();
                         }
                     }
-                    else {
+                    else
+                    {
                         //啥也没找到,默认优先香港服务器[主服务器]
-                        list = serverInformationList.OrderBy(c => c.IsMaster).Select(e => new ServerInfoDTO() {
+                        list = serverInformationList.OrderBy(c => c.IsMaster).Select(e => new ServerInfoDTO()
+                        {
                             Name = e.Name,
                             Host = e.ServerUrl,
                         }).ToList();
                     }
                 }
-                
-                //todo 处理输出数据
+                //处理输出数据
+                var responses = JsonRpcCodec.DecodeResponsesAsync(responseData, new CancellationToken()).Result;
+                var rpcResults = new List<JsonRpcLite.Services.JsonRpcResponse>();
+                var rpcResulut = new JsonRpcLite.Services.JsonRpcResponse(responses[0].Id);
+                rpcResulut.WriteResult(list);
+                rpcResults.Add(rpcResulut);
+                responseData = JsonRpcCodec.EncodeResponsesAsync(rpcResults.ToArray(), new System.Threading.CancellationToken()).Result;
+                return new PluginProcessResult(responseData, false);
             }
             catch (Exception ex)
             {
@@ -160,7 +190,7 @@ namespace WingCloudServer.Plugin
             }
             return new PluginProcessResult(responseData, false);
         }
-    
+
         /// <summary>
         /// ip地址转long
         /// </summary>
@@ -194,7 +224,7 @@ namespace WingCloudServer.Plugin
             double result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2))) * EARTH_RADIUS;
             return result;
         }
- 
+
         /// <summary>
         /// 经纬度转化成弧度
         /// </summary>
@@ -210,22 +240,24 @@ namespace WingCloudServer.Plugin
         /// </summary>
         /// <param name="d"></param>
         /// <returns></returns>
-        private IPServiceResult GetIpLocationInfo(string ip) {
+        private IPServiceResult GetIpLocationInfo(string ip)
+        {
             IPServiceResult info = new IPServiceResult();
-            string key = "4Z3BZ-L5RK6-MJ5SC-EXNFA-3V7PH-RSB3U";//此处要改成配置
-            var url = $"https://apis.map.qq.com/ws/location/v1/ip?ip={ip}&key={key}";
+            var url = string.Format(_ipLocationServiceUrl,ip);
             try
             {
                 var json = HttpGet(url);
-                if (!string.IsNullOrEmpty(json)) {
+                if (!string.IsNullOrEmpty(json))
+                {
                     var serviceGuideInfo = JsonConvert.DeserializeObject<IPServiceGuide>(json);
-                    if (serviceGuideInfo != null && serviceGuideInfo.status == 0 && serviceGuideInfo.result != null) 
+                    if (serviceGuideInfo != null && serviceGuideInfo.status == 0 && serviceGuideInfo.result != null)
                     {
                         info = serviceGuideInfo.result;
                     }
                 }
             }
-            catch(Exception ex) {
+            catch (Exception ex)
+            {
                 //异常处理
             }
             return info;
@@ -256,7 +288,7 @@ namespace WingCloudServer.Plugin
                 request = (HttpWebRequest)WebRequest.Create(url);
 
                 request.Method = "GET";
-                
+
                 //获取服务器返回
                 response = (HttpWebResponse)request.GetResponse();
 
@@ -293,17 +325,17 @@ namespace WingCloudServer.Plugin
         /// <summary>
         /// 状态码;正常为0
         /// </summary>
-        public int status { get; set;}
+        public int status { get; set; }
 
         /// <summary>
         /// 响应信息
         /// </summary>
-        public string message { get; set;}
+        public string message { get; set; }
 
         /// <summary>
         /// 响应结果
         /// </summary>
-        public IPServiceResult result { get; set;}
+        public IPServiceResult result { get; set; }
     }
 
     /// <summary>
@@ -314,17 +346,17 @@ namespace WingCloudServer.Plugin
         /// <summary>
         /// ip地址
         /// </summary>
-        public string ip { get; set;}
+        public string ip { get; set; }
 
         /// <summary>
         /// 经纬度信息
         /// </summary>
-        public IPServiceLocationResult location { get; set;}
+        public IPServiceLocationResult location { get; set; }
 
         /// <summary>
         /// 地区信息
         /// </summary>
-        public IPServiceNationResult ad_info { get; set;}
+        public IPServiceNationResult ad_info { get; set; }
     }
 
     /// <summary>
@@ -335,12 +367,12 @@ namespace WingCloudServer.Plugin
         /// <summary>
         /// 纬度
         /// </summary>
-        public string lat { get; set;}
+        public double lat { get; set; }
 
         /// <summary>
         /// 经度
         /// </summary>
-        public string lng { get; set;}
+        public double lng { get; set; }
     }
 
     /// <summary>
@@ -351,27 +383,27 @@ namespace WingCloudServer.Plugin
         /// <summary>
         /// 国家
         /// </summary>
-        public string nation { get; set;}
+        public string nation { get; set; }
 
         /// <summary>
         /// 省份
         /// </summary>
-        public string province { get; set;}
+        public string province { get; set; }
 
         /// <summary>
         /// 城市
         /// </summary>
-        public string city { get; set;}
+        public string city { get; set; }
 
         /// <summary>
         /// 
         /// </summary>
-        public string district { get; set;}
+        public string district { get; set; }
 
         /// <summary>
         /// 编码
         /// </summary>
-        public string adcode { get; set;}
+        public string adcode { get; set; }
     }
 
     /// <summary>
@@ -382,6 +414,6 @@ namespace WingCloudServer.Plugin
         /// <summary>
         /// 最短距离
         /// </summary>
-        public double BeelineDistance { get; set;}
+        public double BeelineDistance { get; set; }
     }
 }

+ 8 - 5
src/WingServer.cs

@@ -41,15 +41,14 @@ namespace WingCloudServer
             _rpcHttpServer.UseEngine(jsonRpcHttpServerEngine);
         }
 
-       
+
 
         private TokenVerifyPlugin tokenVerifyPlugin;
         private IPAddressPlugin ipAddressPlugin;
+        private ServerListPlugin serverListPlugin;
+
 
-    
-        
 
- 
 
         /// <summary>
         /// Start server to load all service
@@ -60,6 +59,7 @@ namespace WingCloudServer
             //按注册顺序执行
             jsonRpcHttpServerEngine.RegisterPlugin(tokenVerifyPlugin);
             jsonRpcHttpServerEngine.RegisterPlugin(ipAddressPlugin);
+            jsonRpcHttpServerEngine.RegisterPlugin(serverListPlugin);
             _rpcInProcessServer.Start();
             _rpcHttpServer.Start();
         }
@@ -192,7 +192,10 @@ namespace WingCloudServer
             ipAddressPlugin = new IPAddressPlugin();
             _rpcHttpServer.RegisterService(typeof(IIPAddressPlugin), ipAddressPlugin);
             ipAddressPlugin.Load(rpcClientPool);
- 
+            serverListPlugin = new ServerListPlugin();
+            _rpcHttpServer.RegisterService(typeof(IServerListPlugin), serverListPlugin);
+            serverListPlugin.Load(rpcClientPool);
+
         }
 
         private Type LoadService(string folder, object serviceName)

+ 2 - 2
src/appsettings.json

@@ -6,7 +6,7 @@
     "MasterUrl": ""
   },
   "Gateway": {
-    "Host": "http://127.0.0.1/"
+    "Host": "http://192.168.6.28:8303/"
   },
   "Log": {
     "Level": "info",
@@ -76,7 +76,7 @@
       "Apps": "mongod.bat,sms.bat,"
   },
   "FastServer": {
-    "ServerHost": "http://127.0.0.1:9304/"
+    "IpLocationServiceUrl":"https://apis.map.qq.com/ws/location/v1/ip?ip={0}&key=4Z3BZ-L5RK6-MJ5SC-EXNFA-3V7PH-RSB3U"
   },
   "Email": {
     "EmailUserName": "vcloud@vinno.com",