Ejemplo n.º 1
0
        public async Task <int> CheckOrCreate(string phone)
        {
            var result = await _dns.ResolveServiceAsync("service.consul", _options.Value.ServiceName);

            var addressList = result.First().AddressList;
            var address     = addressList.Any() ? addressList.First().ToString() : result.First().HostName;
            var port        = result.First().Port;

            userServiceUrl = $"http://{address}:{port}/";


            Dictionary <string, string> form = new Dictionary <string, string> {
                { "phone", phone }
            };
            var content = new FormUrlEncodedContent(form);

            var response = await _httpClient.PostAsync(userServiceUrl + "api/user/check-or-create", content);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result1 = await response.Content.ReadAsStringAsync();

                int.TryParse(result1, out int userId);
                return(userId);
            }
            return(0);
        }
Ejemplo n.º 2
0
        public async Task <Uri> Resolve(string serviceName)
        {
            var dnsResult = await _dns.ResolveServiceAsync(_baseDnsDiscovery.BaseDomain, serviceName);


            if (dnsResult.Length > 0)
            {
                Console.WriteLine("Founded Dns");

                string address      = "";
                var    service      = dnsResult.First();
                var    firstAddress = service.AddressList.FirstOrDefault();
                if (firstAddress == null)
                {
                    address = service.HostName;
                }
                else
                {
                    address = firstAddress.ToString();
                }

                var port = dnsResult.First().Port;

                return(new Uri($"http://{address}:{port}"));
            }
            else
            {
                throw new EndpointDiscoveryException();
            }
        }
Ejemplo n.º 3
0
        public async Task <int> CheckOrCreate(string phone)
        {
            var result = await _dns.ResolveServiceAsync("service.consul", _options.Value.UserServiceName);

            var address = result.First().AddressList.FirstOrDefault();
            var port    = result.First().Port;


            var form = new Dictionary <string, string> {
                { "phone", phone }
            };
            var content  = new FormUrlEncodedContent(form);
            var response = await _httpClient.PostAsync(_userServiceUrl + "/api/user/check-or-create", content);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var userId = await response.Content.ReadAsStringAsync();

                int.TryParse(userId, out int intUserId);
                return(intUserId);
            }

            return(0);
            //throw new NotImplementedException();
        }
Ejemplo n.º 4
0
 public UserService(Resillience.IHttpClient client, IDnsQuery dnsQuery)
 {
     _client   = client;
     _logger   = Startup.logger;
     _userUrls = new List <string>();
     try
     {
         //因为是查询consul的某个服务的服务实例,根据consul文档格式为:服务名.service.consul
         //所以第一个参数是:service.consul
         //第二参数是要查询的服务名
         var services = dnsQuery.ResolveServiceAsync("service.consul", "user").Result;
         foreach (var service in services)
         {
             //返回查询到user服务下的第1个服务实例的ip和端口,给这个identity sever4去进行验证使用
             var host = service.AddressList.First();
             var port = service.Port;
             var url  = $"http://{host}:{port}";
             //存储全部能用的user服务的实例地址
             _userUrls.Add(url);
         }
     }
     catch (Exception e)
     {
     }
 }
Ejemplo n.º 5
0
        public async Task <int> CheckOrCreate(string phone)
        {
            var result = await _dns.ResolveServiceAsync("service.consul", _options.Value.ServiceName);

            var addressList = result.First().AddressList;
            var address     = addressList.Any() ? addressList.First().ToString() : result.First().HostName.TrimEnd('.');
            var port        = result.First().Port;

            userServiceUrl = $"http://{address}:{port}/";
            _logger.LogInformation("i am  the internal  logging framework;");
            Dictionary <string, string> form = new Dictionary <string, string> {
                { "phone", phone }
            };
            var content = new FormUrlEncodedContent(form);

            try
            {
                var response = await _httpClient.PostAsync(userServiceUrl + "api/user/check-or-create", content);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var result1 = await response.Content.ReadAsStringAsync();

                    int.TryParse(result1, out int userId);
                    return(userId);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("重试失败。。。。。" + ex.Message);
                return(0);
            }

            return(0);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 从Consul发现用户服务地址
        /// </summary>
        /// <returns></returns>
        private async Task <string> GetApplicateUrlFromConsulAsync()
        {
            try
            {
                var policyRetry = Policy.Handle <InvalidOperationException>()
                                  .WaitAndRetryAsync(
                    3,
                    retryTimespan => TimeSpan.FromSeconds(Math.Pow(2, retryTimespan)),
                    (exception, timespan, retryCount, context) =>
                {
                    //重试期间进行日志记录
                    //exception 异常信息
                    //timespan 时间间隔
                    //retryCount 当前重试次数
                    //content 类容
                    var msg = $"第 {retryCount} 次进行错误重试 " +
                              $"of {context.PolicyKey} " +
                              $"at {context.ExecutionKey}, " +
                              $"due to: {exception}.";
                    _ilogger.LogWarning(msg);
                    _ilogger.LogDebug(msg);
                });
                var policyBreak = Policy.Handle <InvalidOperationException>()
                                  .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1),
                                                       (exctption, timespan) =>
                {
                    _ilogger.LogTrace("断路器打开");
                },
                                                       () =>
                {
                    _ilogger.LogTrace("断路器关闭");
                });

                var policyWary = Policy.WrapAsync(policyRetry, policyBreak);


                var appUrl1 = await policyWary.ExecuteAsync(async() =>
                {
                    var result      = await _dnsQuery.ResolveServiceAsync("service.consul", _serviceOption.DiscoverServiceName);
                    var addressList = result.First().AddressList;
                    var address     = addressList.Any() ? addressList.First().ToString() : result.First().HostName;
                    var port        = result.First().Port;
                    var appUrl      = $"http://{address}:{port}{QueryAction}";
                    return(appUrl);
                });

                return(appUrl1);
            }
            catch (Exception ex)
            {
                _ilogger.LogError($"从Consul发现UserApi地址,在重试3次后失败" + ex.Message + ex.StackTrace);
                return("");
            }
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> DoSomething()
        {
            var result = await _dnsQuery.ResolveServiceAsync("service.consul", _options.Value.ServiceName);

            var addressList = result.First().AddressList;
            var host        = addressList.Any() ? addressList.First().ToString() : result.First().HostName;
            var port        = result.First().Port;
            var url         = $"http://{host}:{port}";

            return(Ok(result));
        }
Ejemplo n.º 8
0
        private async Task <List <string> > PullHostFromConsul(string serviceName)
        {
            var hostList = await _dnsQuery.ResolveServiceAsync("service.consul", serviceName);

            List <string> hosts = new List <string>();

            foreach (var hostItem in hostList)
            {
                hosts.Add($"{hostItem.AddressList.First().ToString()}:{hostItem.Port}");
            }
            return(hosts);
        }
Ejemplo n.º 9
0
        private async Task <string> ByDnsClient()
        {
            var result = await _dns.ResolveServiceAsync("service.consul", _options.Value.DiscoveryServiceName);

            var address = result.First();

            using (var client = new HttpClient())
            {
                var _userApiUrl   = $"http://{address.HostName}:{address.Port}";
                var serviceResult = await client.GetStringAsync($"{_userApiUrl}/api/user");

                return(serviceResult);
            }
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Get()
        {
            var result = await _dns.ResolveServiceAsync("service.consul", _options.ServiceName);

            var firstHost = result.First();
            var address   = firstHost.AddressList.Any() ? firstHost.AddressList.FirstOrDefault().ToString() : firstHost.HostName;
            var port      = firstHost.Port;

            using (var client = new HttpClient())
            {
                var serviceResult = await client.GetStringAsync($"http://{address}:{port}/api/user");

                return(Content(serviceResult));
            }
        }
Ejemplo n.º 11
0
        public async Task <string> Get()
        {
            var result = await _dns.ResolveServiceAsync("service.consul", _options.Value.DiscoveryServiceName);

            var address = result.First().AddressList.FirstOrDefault();
            var port    = result.First().Port;

            using (var client = new HttpClient())
            {
                _userApiUrl = $"http://{address}:{port}";
                var serviceResult = await client.GetStringAsync($"{_userApiUrl}/api/user");

                return(serviceResult);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 根据API服务名称解析出对应的IP地址和端口
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns>返回IP地址和端口(如:192.168.1.100:5000)</returns>
        private async Task <string> ResolveServiceAddressAsync(string serviceName)
        {
            var result = await _dnsQuery.ResolveServiceAsync("service.consul", serviceName);

            var firstHost = result.FirstOrDefault();

            if (firstHost == null)
            {
                throw new Exception($"未发现{serviceName}的服务实例");
            }
            var address = firstHost.AddressList.Any() ? firstHost.AddressList.FirstOrDefault().ToString() : firstHost.HostName;
            var port    = firstHost.Port;

            return($"{address}:{port}");
        }
Ejemplo n.º 13
0
        public async Task <string> Get()
        {
            var service = await _dns.ResolveServiceAsync("service.consul", _options.Value.ServiceName);

            var address = service.First().AddressList.FirstOrDefault();
            var port    = service.First().Port;

            var response = await _httpClient.GetAsync(_userServiceUrl + "/api/users");

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var result = await response.Content.ReadAsStringAsync();

                return(result);
            }
            return(string.Empty);
        }
        public async Task <string> SearchByNameAsync(string serviceName)
        {
            var result = await _dnsQuery.ResolveServiceAsync(serviceName);

            if (result is null || result.Length <= 0)
            {
                return(null);
            }

            var record = result[0];

            if (record.AddressList?.Length <= 0)
            {
                return(null);
            }

            return($"http://{record.AddressList[0]}:{record.Port}");
        }
Ejemplo n.º 15
0
        public async Task <List <ContactDto> > GetContactsAsync(int userId)
        {
            var hostEntries = await _dns.ResolveServiceAsync("service.consul", _dependencyService.ContactServiceName);

            if (hostEntries == null || hostEntries.Length <= 0)
            {
                var msg = $"在Service.consul:{_options.Consul.DnsEndpoint.ToIPEndPoint()} 中未找到 ServiceName={_dependencyService.ContactServiceName}";
                _logger.LogWarning(msg);
                throw new ArgumentNullException(nameof(_dependencyService.ContactServiceName), msg);
            }
            var hostEntry = hostEntries.First();

            // TBD 需要传Token
            var result = await _httpClient.GetStringAsync($"http://{hostEntry.HostName}:{hostEntry.Port}/api/contacts/" + userId);


            return(JsonConvert.DeserializeObject <List <ContactDto> >(result));
        }
Ejemplo n.º 16
0
        public async Task <IEnumerable <string> > GetAsync()
        {
            var dnsResult = await _dns.ResolveServiceAsync("service.consul", "story");

            if (dnsResult.Length > 0)
            {
                var result  = dnsResult.First();
                var address = result.AddressList.Any() ? result.AddressList.FirstOrDefault().ToString() : result.HostName.TrimEnd('.');
                var port    = result.Port;

                using (var client = new HttpClient())
                {
                    var serviceResult = await client.GetStringAsync($"http://{address}:{port}/api/stories");

                    return(new string[] { "users-1", "users-2", serviceResult });
                }
            }

            return(new string[] { "users-1", "users-2" });
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> Index()
        {
            var model = new IndexViewModel()
            {
                DnsResult = await _dns.ResolveServiceAsync("service.consul", "dataservice")
            };

            if (model.DnsResult.Length > 0)
            {
                var firstAddress = model.DnsResult.First().AddressList.FirstOrDefault();
                var port         = model.DnsResult.First().Port;

                using (var client = new HttpClient())
                {
                    model.ServiceResult = await client.GetStringAsync($"http://{firstAddress}:{port}/Values");
                }
            }

            return(View(model));
        }
Ejemplo n.º 18
0
        public async Task <RestResult> SendAsync(string service, string api, HttpMethod method, object data = null, string authorizationToken = null, string requestId = null, string authorizationMethod = "Bearer")
        {
            var entries = await _dnsQuery.ResolveServiceAsync("service.consul", service);

            if (entries == null || !entries.Any())
            {
                throw new ArgumentException();
            }

            var entry = entries.FirstOrDefault();

            var ip             = $"http://{entry.HostName.Substring(0, entry.HostName.Length - 1)}:{entry.Port}/{api}";
            var requestMessage = new HttpRequestMessage(method, ip);

            if (data != null)
            {
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
            }

            SetAuthorizationHeader(requestMessage);

            if (authorizationToken != null)
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue(authorizationMethod, authorizationToken);
            }

            if (requestId != null)
            {
                requestMessage.Headers.Add("x-requestid", requestId);
            }

            var rsp = await _client.SendAsync(requestMessage);

            if (rsp.StatusCode == HttpStatusCode.InternalServerError)
            {
                throw new HttpRequestException();
            }
            var str = await rsp.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <RestResult>(str));
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Index()
        {
            var model = new IndexViewModel()
            {
                DnsResult = await _dns.ResolveServiceAsync("service.consul", "descovery")
            };

            if (model.DnsResult.Length > 0)
            {
                var result  = model.DnsResult.First();
                var address = result.AddressList.Any() ? result.AddressList.FirstOrDefault().ToString() : result.HostName.TrimEnd('.');
                var port    = result.Port;

                using (var client = new HttpClient())
                {
                    model.ServiceResult = await client.GetStringAsync($"http://{address}:{port}/api/values");
                }
            }

            return(View(model));
        }
Ejemplo n.º 20
0
        public async Task <UserInfo> CheckOrAddUserAsync(string phone)
        {
            var hostEntries = await _dns.ResolveServiceAsync("service.consul", _dependencyService.UserServiceName);

            if (hostEntries == null || hostEntries.Length <= 0)
            {
                var msg = $"在Service.consul:{_options.Consul.DnsEndpoint.ToIPEndPoint()} 中未找到 ServiceName={_dependencyService.UserServiceName}";
                _logger.LogWarning(msg);
                throw new ArgumentNullException(nameof(_dependencyService.UserServiceName), msg);
            }
            var hostEntry = hostEntries.First();

            var data = new Dictionary <string, string>()
            {
                { "phone", phone }
            };
            var response = await _httpClient.PostAsync($"http://{hostEntry.HostName}:{hostEntry.Port}/api/users/check-or-create", data);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(await response.Content.ReadAsAsync <UserInfo>());
            }
            return(null);
        }
Ejemplo n.º 21
0
 public async Task <IActionResult> ResolveService()
 {
     // /api/servicediscovery/resolveService
     return(Ok(await _dns.ResolveServiceAsync("service.consul", _consulConfig.Value.ServiceName)));
 }