Пример #1
0
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder(config =>
            {
                config.ServiceName  = "MyServiceA";
                config.LoadBalancer = TypeLoadBalancer.RoundRobin;
                config.UriScheme    = Uri.UriSchemeHttp;
            });

            var httpClient = new HttpClient();

            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------调用第{i}次------------");
                try
                {
                    var uri = myServiceA.BuildAsync("health").Result;
                    Console.WriteLine($"{DateTime.Now}--正在调用:{uri}");
                    var content = httpClient.GetStringAsync(uri).Result;
                    Console.WriteLine($"结果:{content}");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"异常:{e.Message}");
                }

                Thread.Sleep(1000);
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "MyServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });

            var httpClient = new HttpClient();

            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                try
                {
                    var uri = myServiceA.BuildAsync("health").Result;
                    Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                    var content = httpClient.GetStringAsync(uri).Result;
                    Console.WriteLine($"调用结果:{content}");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"调用异常:{e.GetType()}");
                }
                Task.Delay(1000).Wait();
            }
        }
Пример #3
0
        public async Task <UserIdentity> CheckOrCreate(string phone)
        {
            #region ServicesDiscovery
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            var _userServiceUrl = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName  = "UserApi";
                builder.LoadBalancer = TypeLoadBalancer.RandomLoad;
                builder.UriScheme    = Uri.UriSchemeHttp;
            }).BuildAsync("/api/user/checkcreate");
            #endregion

            var form = new Dictionary <string, string>()
            {
                { "phone", phone }
            };
            try
            {
                var response = await _httpClient.PostAsync(_userServiceUrl.ToString(), new  FormUrlEncodedContent (form));

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

                    return(JsonConvert.DeserializeObject <UserIdentity>(result));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("在重试之后失败");
                throw new Exception(ex.Message);
            }
            return(null);
        }
Пример #4
0
        public async Task <List <ShopResponseDto> > GetAllShop()
        {
            #region ServicesDiscovery
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            var Url = await serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName  = "BasicApi";
                builder.LoadBalancer = TypeLoadBalancer.RandomLoad;
                builder.UriScheme    = Uri.UriSchemeHttp;
            }).BuildAsync("/Api/Shop/GetShopList");

            #endregion
            try
            {
                var response = await _httpClient.GetAsync(Url);

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

                    var res = JsonConvert.DeserializeObject <CoreResult <List <ShopResponseDto> > >(result);
                    return(res.Result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("在重试之后失败");
                throw new Exception(ex.Message);
            }
            return(null);
        }
Пример #5
0
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "MyServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });

            var httpClient = new HttpClient();

            // Polly如果再微服务里,主要是用在跨服务调用上,虽然他很很牛B,但还是把它当做try catch
            // 关于这节课,大家有收获 回复个666
            // Polly有BUG?你也可以点用其他API
            // Polly可以.NET Core里的HTTPFactory集合使用,用起来更爽了
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                try
                {
                    var uri = myServiceA.BuildAsync("health").Result;
                    Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                    var content = httpClient.GetStringAsync(uri).Result;
                    Console.WriteLine($"调用结果:{content}");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"调用异常:{e.GetType()}");
                }
                Task.Delay(1000).Wait();
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            #region 读取服务

            //ConsulServiceProvider consulServiceProvider = new ConsulServiceProvider("http://127.0.0.1:8500");
            //string serviceName = "MyServiceA";
            //Task<List<string>> serviceList = consulServiceProvider.GetServicesAsync(serviceName);

            //foreach (var item in serviceList.Result)
            //{
            //    Console.WriteLine(item);
            //}
            #endregion


            #region 生成接口地址并访问
            //生成 ServiceBuilder方式1:
            //ServiceBuilder serviceBuilder = new ServiceBuilder()
            //{
            //    LoadBalancer = new RoundRoinLoadBalancer(),
            //    ServiceName = "MyServiceA",
            //    ServiceProvider = new ConsulServiceProvider("http://127.0.0.1:8500"),
            //    UriScheme = Uri.UriSchemeHttp
            //};

            //生成 ServiceBuilder方式2(用建造者模式,比较优雅,推荐):
            var seviceProvider = new ConsulServiceProvider("http://127.0.0.1:8500");
            var serviceBuilder = seviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName  = "MyServiceA";
                builder.LoadBalancer = TypeLoadBalancer.RandomLoad;// new RoundRoinLoadBalancer();
                builder.UriScheme    = Uri.UriSchemeHttp;
            });

            HttpClient httpClient = new HttpClient();
            for (int i = 0; i < 5; i++)
            {
                Task <Uri> url    = serviceBuilder.BuildAsync("/Api/Health");
                Uri        apiUrl = url.Result;

                Console.WriteLine($"----------------第{i}次请求-----------------------");
                Console.WriteLine($"{DateTime.Now}-正在调用{apiUrl}");

                var content = httpClient.GetStringAsync(apiUrl).Result;
                Console.WriteLine($"调用结果:{content}");

                Task.Delay(1000).Wait();
            }

            #endregion

            Console.WriteLine("Hello World!");
        }
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "MyServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });

            var httpClient = new HttpClient();
            var policy     = PolicyBuilder.CreatePolly();

            // 重试轮询+熔断降级

            // 你去一个商场消费,某个商品卖断货,你可能寻求次级品,(提供的服务,就降级了)
            // 服务A访问服务B,这个B老是失败,你失败多了,如果是高并发就会引发雪崩,我降级服务,我自己准一套备用的。

            // 返回一个个空数据

            // 源码肯定有,
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                policy.Execute(() =>
                {
                    try
                    {
                        // 根据负载均衡获取具体服务地址
                        // consul崩了,仍然会被我们的polly接住
                        // 服务和服务间调用也一样
                        // 服务间传消息?直接调用API,MQ
                        // 每个有服务调用的服务应用,都用POLLY,服务挂了
                        var uri = myServiceA.BuildAsync("/api/order").Result;
                        Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetStringAsync(uri).Result;
                        Console.WriteLine($"调用结果:{content}");
                    }
                    catch (Exception e)
                    {
                        // 如果你要在策略里捕捉异常,如果这个异常还是你定义的故障,一定要把这异常再抛出来
                        Console.WriteLine($"调用异常:{e.GetType()}");
                        throw;
                    }
                });
                Task.Delay(1000).Wait();
            }
        }
Пример #8
0
        public async Task <IActionResult> Index()
        {
            CoreResult coreResult = new CoreResult();

            #region ServiceDiscovery

            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            var _userServiceUrl = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName  = "UserApi";
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                builder.UriScheme    = Uri.UriSchemeHttp;
            }).BuildAsync("/api/user/servicesdiscovery").Result;

            #endregion

            var polly = PolicyBuilder.CreatePolly();
            polly.Execute(() => {
                try
                {
                    var form = new Dictionary <string, string>()
                    {
                        { "phone", "18650482503" }
                    };
                    var response = _httpClient.PostAsync(_userServiceUrl.ToString(), new FormUrlEncodedContent(form)).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        coreResult.Success(response.Content.ReadAsStringAsync().Result);
                    }
                    else
                    {
                        coreResult.Failed(response.Content.ReadAsStringAsync().Result);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("在重试之后失败");
                    throw new Exception(ex.Message);
                }
            });

            return(Content(coreResult.Message));
        }
Пример #9
0
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "MyServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });

            var httpClient = new HttpClient();
            var policy     = PolicyBuilder.CreatePolly();

            // 重试轮询+熔断降级
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                policy.Execute(() =>
                {
                    try
                    {
                        // 根据负载均衡获取具体服务地址
                        // consul崩了,仍然会被我们的polly接住
                        // 服务和服务间调用也一样
                        // 服务间传消息?直接调用API,MQ
                        // 每个有服务调用的服务应用,都用POLLY
                        //var uri = myServiceA.BuildAsync("/api/order").Result; //这个没有实现api/order 可以测试抛出异常
                        var uri = myServiceA.BuildAsync("/health").Result;
                        Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetStringAsync(uri).Result;
                        Console.WriteLine($"调用结果:{content}");
                    }
                    catch (Exception e)
                    {
                        // 如果你要在策略里捕捉异常,如果这个异常还是你定义的故障,一定要把这异常再抛出来
                        Console.WriteLine($"调用异常:{e.GetType()}");
                        throw;
                    }
                });
                Task.Delay(1000).Wait();
            }
        }
Пример #10
0
        public async Task GetServiceDiscovery()
        {
            var serviceDiscoveryProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            #region 获取服务节点列表
            //var serviceAList = await serviceDiscoveryProvider.GetServicesAsync("ServiceA");
            //return serviceAList;
            #endregion

            var serviceA = serviceDiscoveryProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "ServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });
            var httpClient = new HttpClient();
            var policy     = PolicyBuilder.CreatePolly();

            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                policy.Execute(() =>
                {
                    try
                    {
                        var uri = serviceA.BuildAsync("health").Result;
                        System.Diagnostics.Debug.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetStringAsync(uri).Result;
                        System.Diagnostics.Debug.WriteLine($"调用结果:{content}");
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine($"调用异常:{e.GetType()}");
                    }
                });
                Task.Delay(1000).Wait();
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            //创建consul实例并配置consul注册地址 127.0.0.1:8500
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500/"));

            //需要调用构建的服务类型及负载均衡模式等信息的配置
            var serviceStudent = serviceProvider.CreateServiceBuilder(builder =>
            {
                //消费方需使用的服务名称
                builder.ServiceName = "Student";
                //服务调用的负载均衡模式
                builder.LoadBalancer = TypeLoadBalancer.RoundRobinLoad;
                //服务请求协议 http/https
                builder.UriScheme = Uri.UriSchemeHttp;
            });


            var httpClient = new HttpClient();

            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"--------------第{i}次请求---------------");

                try
                {
                    //拼接服务调用的具体方法
                    var uri = serviceStudent.BuilderAsync("/api/Default/GetList").Result;
                    Console.WriteLine($"{DateTime.Now.ToString()}--正在调用:{uri}");
                    //发送http的get请求,返回请求服务接口地址后具体的返回信息;此处是调用的student服务的check方法,返回的string值“1”
                    var content = httpClient.GetStringAsync(uri).Result;
                    Console.WriteLine($"调用结果:{content}");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"调用异常信息:{e.GetType()}");
                }
                Task.Delay(1000).Wait();
            }
        }
Пример #12
0
        public async Task <UserInfo> GetBaseUserInfoAsync(int userId)
        {
            #region ServicesDiscovery
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            var _userServiceUrl = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName  = "UserApi";
                builder.LoadBalancer = TypeLoadBalancer.RandomLoad;
                builder.UriScheme    = Uri.UriSchemeHttp;
            });
            #endregion

            var client   = new HttpClient();
            var response = client.GetStringAsync(_userServiceUrl + "/api/user/getuserinfo/" + userId).Result;
            if (!string.IsNullOrEmpty(response))
            {
                var userInfo = JsonConvert.DeserializeObject <UserInfo>(response);
                return(userInfo);
            }
            return(null);
        }
Пример #13
0
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder((builder) =>
            {
                builder.ServiceName  = "MyServiceA";
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                builder.UriScheme    = Uri.UriSchemeHttp;
            });


            var policy = PolicyBuilder.CreatePolly();

            var httpClient = new HttpClient();

            for (int i = 0; i < 100; i++)
            {
                policy.Execute(() =>
                {
                    try
                    {
                        var uri = myServiceA.BuildAsync("/health").Result;
                        Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetAsync(uri).Result;
                        Console.WriteLine($"调用结果:{content?.StatusCode}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("业务逻辑异常 ex:" + ex.GetType());
                        throw;
                    }
                });

                Task.Delay(1000).Wait();
            }

            Console.Read();
        }