예제 #1
0
        static void Main(string[] args)
        {
            using (var http = new HttpClient())
            {
                SendSms sms = new SendSms
                {
                    Msg      = "hello",
                    PhoneNum = "188"
                };
                RestTemplate rest = new RestTemplate(http);
                rest.ConsulServerUrl = "http://127.0.0.1:8500";
                var result = rest.PostAsync("http://MsgService/api/SMS/Send_MI", sms).Result;
                Console.WriteLine(result.StatusCode);

                var getResult = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product").Result;
                foreach (var g in getResult.Body)
                {
                    Console.WriteLine(g.Id + " " + g.Name);
                }

                var getResult2 = rest.GetForEntityAsync <Product>("http://ProductService/api/Product/1").Result;
                Console.WriteLine(getResult2.Body.Name);
            }


            Console.ReadKey();
        }
예제 #2
0
        private static void Main(string[] args)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient);

                Console.WriteLine("---查询数据---------");
                var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/").Result;
                Console.WriteLine(ret1.StatusCode);
                if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in ret1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }

                Console.WriteLine("---新增数据---------");
                Product newP = new Product();
                newP.Id    = 888;
                newP.Name  = "辛增";
                newP.Price = 88.8;
                var ret = rest.PostAsync("http://ProductService/api/Product/", newP).Result;
                Console.WriteLine(ret.StatusCode);
            }
            Console.ReadKey();
        }
예제 #3
0
        static void Main(string[] args)
        {
            using (HttpClient http = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(http);
                rest.ConsulServerUrl = "http://127.0.0.1:8500";

                /* SendSms sms = new SendSms();
                 * sms.msg = "您好,欢迎";
                 * sms.phoneNum = "189189";
                 * var resp = rest.PostAsync("http://MsgService/api/SMS/Send_MI", sms).Result;
                 * Console.WriteLine(resp.StatusCode);*/
                /*
                 * var res = rest.GetForEntityAsync<Product[]>("http://ProductService/api/Product").Result;
                 * Console.WriteLine(res.StatusCode);
                 * foreach(var p in res.Body)
                 * {
                 * Console.WriteLine(p.Id+p.Name);
                 * }*/
                var res = rest.GetForEntityAsync <Product>("http://ProductService/api/Product/1").Result;
                Console.WriteLine(res.StatusCode);
                Console.WriteLine(res.Body.Name);
            }

            Console.ReadKey();
        }
예제 #4
0
 static void Main(string[] args)
 {
     //获取服务
     using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
     {
         var services = consulClient.Agent.Services().Result.Response;
         foreach (var service in services.Values)
         {
             Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
         }
     }
     //消费服务
     using (HttpClient httpClient = new HttpClient())
     {
         RestTemplate rest = new RestTemplate(httpClient);
         rest.ConsulServerUrl = "http://127.0.0.1:8500";
         var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/").Result;
         Console.WriteLine(ret1.StatusCode);
         if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
         {
             foreach (var p in ret1.Body)
             {
                 Console.WriteLine($"id={p.Id},name={p.Name}");
             }
         }
     }
 }
예제 #5
0
        public void CheckConsul()
        {
            RestTemplate restTemplate = new RestTemplate();
            var          result       = restTemplate.GetForEntityAsync <string[]>("http://Lucky.Project.API.Service/api/Values").Result;

            Assert.Equal(2, result.Body.Length);
        }
예제 #6
0
        /// <summary>
        /// RestTemplateCore 方式
        /// </summary>
        /// <returns></returns>
        static async Task RestTemplateCoreAsync()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient);
                Console.WriteLine("---查询数据---------");
                var resp1 = await rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product");

                Console.WriteLine(resp1.StatusCode);
                if (resp1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in resp1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }
                Console.WriteLine("---新增数据---------");
                Product newP = new Product();
                newP.Id    = 888;
                newP.Name  = "辛增";
                newP.Price = 88.8;
                var resp2 = await rest.PostAsync("http://ProductService/api/Product", newP);

                Console.WriteLine(resp2.StatusCode);
            }
        }
예제 #7
0
        static void Main(string[] args)
        {
            //@杨中科 封装 负载均衡模板
            //地址:https://github.com/yangzhongke/RuPeng.RestTemplateCore
            //开发完成发布到Nuget:https://www.nuget.org/packages/RestTemplateCore
            // Install-Package RestTemplateCore -Version 1.0.1
            //使用 模板(简单的负载均衡,简化http请求)

            using (HttpClient http = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(http);
                rest.ConsulServerUrl = "http://127.0.0.1:8500";


                #region Post请求
                //SendSms sms = new SendSms() { phoneNum = "119119", msg = "着火了主要火了" };
                //var s = rest.PostAsync("http://MsgService/api/SMS/Send_MI", sms).Result;
                //Console.WriteLine(s.StatusCode);
                #endregion

                #region get请求

                var result = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product").Result;
                Console.WriteLine(result.StatusCode);
                foreach (var p in result.Body)
                {
                    Console.WriteLine($"id:{p.Id} Name:{p.Name}");
                }
                #endregion
            }
            Console.ReadKey();
        }
예제 #8
0
        static void Main(string[] args)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient, "http://127.0.0.1:8500");

                Console.WriteLine("---querying---------");
                var headers = new HttpRequestMessage().Headers;
                headers.Add("aa", "666");
                var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/", headers).Result;
                Console.WriteLine(ret1.StatusCode);
                if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in ret1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }

                Console.WriteLine("---add new---------");
                Product newP = new Product();
                newP.Id    = 888;
                newP.Name  = "xinzeng";
                newP.Price = 88.8;
                var ret = rest.PostAsync("http://ProductService/api/Product/", newP).Result;
                Console.WriteLine(ret.StatusCode);
            }
            Console.ReadKey();
        }
예제 #9
0
 static void Main(string[] args)
 {
     using (HttpClient httpClient = new HttpClient())
     {
         RestTemplate rest = new RestTemplate(httpClient);
         var          ret1 = rest.GetForEntityAsync <string []>("http://MsgService/api/values/").Result;
         Console.WriteLine(JsonConvert.SerializeObject(ret1));
     }
     Console.ReadKey();
 }
예제 #10
0
 private static void Demo1()
 {
     // 负载均衡到每台服务器
     for (int i = 0; i < 10; i++)
     {
         RestTemplate rest = new RestTemplate("http://127.0.0.1:8500");
         ResponseEntity <string[]> resp = rest.GetForEntityAsync <string[]>("http://apiservice1/api/values").Result;
         Console.WriteLine(resp.StatusCode + "  " + string.Join(",", resp.Body));
         Thread.Sleep(1000);
     }
 }
예제 #11
0
        static void Main(string[] args)
        {
            RestTemplate rest = new RestTemplate("http://127.0.0.1:8500");
            //RestTemplate把服务的解析和发请求以及响应反序列化帮我们完成
            ResponseEntity <TestUserInfo> resp = rest.GetForEntityAsync <TestUserInfo>("http://apiservice1/api/Home").Result;

            Console.WriteLine(resp.StatusCode);
            Console.WriteLine(String.Join(",", resp.Body));

            Console.ReadKey();
        }
예제 #12
0
        static void Main(string[] args)
        {
            HttpClient httpClient = new HttpClient()
            {
                BaseAddress = new Uri("http://127.0.0.1:8500")
            };
            RestTemplate rest = new RestTemplate(httpClient);
            RestResponseWithBody <List <string> > resp =
                rest.GetForEntityAsync <List <string> >("http://AspNetCoreMicro/api/values").Result;

            Console.WriteLine(resp.StatusCode);
            Console.WriteLine(string.Join(",", resp.Body));
            Console.WriteLine("Hello World!");
        }
예제 #13
0
        private static void Demo3()
        {
            using (HttpClient http = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(http)
                {
                    ConsulServerUrl = "http://127.0.0.1:8500"
                };

                var res = rest.GetForEntityAsync <Product>("http://ProductService/api/Product/1").Result;
                Console.WriteLine(res.StatusCode);
                Console.WriteLine(res.Body.Name);
            }
        }
예제 #14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
            app.UseOcelot().Wait();
            //app.Use(async (context, next) =>
            //{
            //    await context.Response.WriteAsync("First Middleware in. \r\n");
            //    await next.Invoke();
            //    await context.Response.WriteAsync("First Middleware out. \r\n");
            //});

            // app.Use(async (context, next) =>
            // {
            //     await context.Response.WriteAsync("Second Middleware in. \r\n");

            //     // 水管阻塞,封包不往后送
            //     var condition = false;
            //     if (condition)
            //     {
            //         await next.Invoke();
            //     }
            //     await context.Response.WriteAsync("Second Middleware out. \r\n");
            // });

            //app.Map("/second", mapApp =>
            //{
            //    mapApp.Use(async (context, next) =>
            //    {
            //        await context.Response.WriteAsync("Second Middleware in. \r\n");
            //        await next.Invoke();
            //        await context.Response.WriteAsync("Second Middleware out. \r\n");
            //    });
            //    mapApp.Run(async context =>
            //    {
            //        await context.Response.WriteAsync("Second. \r\n");
            //    });
            //});
            //app.UseFirstMiddleware();

            //app.Use(async (context, next) =>
            //{
            //    await context.Response.WriteAsync("Third Middleware in. \r\n");
            //    await next.Invoke();
            //    await context.Response.WriteAsync("Third Middleware out. \r\n");
            //});

            //url重写(新旧改版)  301 302对于用户或者开发者来说没有什么区别  301 主要是告诉浏览器搜索引擎 该网址已经永久转到另外一个网址去了 302是告知搜索引擎,虽然这次被转址,但只是暂时性的。通常用于网站维护时,暂时原网址转移到别的地方,如维护公告页面。

            //var rewrite = new RewriteOptions().AddRewrite("about.aspx", "home/about", skipRemainingRules: true).AddRedirect("first", "home/index", 301);

            //var defaultFilesOptions = new DefaultFilesOptions();
            //defaultFilesOptions.DefaultFileNames.Add("custom.html");
            //app.UseDefaultFiles(defaultFilesOptions);//默认指向到index.html 尝试请求默认文件 默认寻找 default.html default.htm index.html index.htm
            //app.UseStaticFiles();//启用静态文件  注册静态文件的Middleware  默认启用的目录是wwwroot  当request的url找不到时会执行run里面的事件
            //            UseDefaultFiles必须注册在UseStaticFiles之前。
            //如果先注册UseStaticFiles,当URL是 / 时,UseStaticFiles找不到该文件,就会直接回传找不到;所以就没有机会进到UseDefaultFiles
            //app.UseStaticFiles(new StaticFileOptions()
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, @"node_modules")),
            //    RequestPath = new PathString("/third-party"),//这样修改 http://localhost:5000/third-party/example.js指向到项目目录\node_modules\example.js。
            //});
            //app.UseCookiePolicy();

            //app.UseFileServer(new FileServerOptions()
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
            //    RequestPath = new PathString("/StaticFiles"),
            //    EnableDirectoryBrowsing = true
            //});


            app.Run(async(context) =>
            {
                using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
                {
                    //var services = consulClient.Agent.Services().Result.Response;
                    //foreach (var service in services.Values)
                    //{
                    //    await context.Response.WriteAsync($"服务地址:id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
                    //}

                    var services = consulClient.Agent.Services().Result.Response.Values.Where(a => a.Service.Equals("MsgService", StringComparison.OrdinalIgnoreCase));
                    //客户端负载均衡
                    Random r    = new Random();
                    int index   = r.Next(services.Count());
                    var service = services.ElementAt(index);
                    await context.Response.WriteAsync($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");

                    using (HttpClient http = new HttpClient())
                        using (var httpContent = new StringContent("{phoneNum:'119',msg:'help'}", Encoding.UTF8, "application/json"))
                        {
                            var result = http.PostAsync($"http://{service.Address}:{service.Port}/api/SMS/Send_LX", httpContent).Result;
                            await context.Response.WriteAsync(result.StatusCode.ToString());
                        }
                };
                await context.Response.WriteAsync("Hello World!");
                using (HttpClient client = new HttpClient())
                {
                    RestTemplate rest    = new RestTemplate(client);
                    rest.ConsulServerUrl = "http://127.0.0.1:8500";
                    var res = rest.GetForEntityAsync <Product>("http://ProductService/api/Product/1").Result;
                    await context.Response.WriteAsync(res.StatusCode.ToString(), Encoding.UTF8);
                    await context.Response.WriteAsync(res.Body.Name, Encoding.Default);
                }
                try
                {
                    //Policy policy = Policy.Handle<Exception>().WaitAndRetry(100, i => TimeSpan.FromSeconds(i));
                    //policy.Execute(() =>
                    //{
                    //    context.Response.WriteAsync("开始任务");
                    //    if (DateTime.Now.Second % 10 != 0)
                    //    {
                    //        throw new Exception("出错");
                    //    }
                    //    context.Response.WriteAsync("完成任务");
                    //});

                    Policy policy = Policy.Handle <Exception>() //定义所处理的故障
                                    .Fallback(() =>
                    {
                        context.Response.WriteAsync("111");
                    });
                    policy = policy.Wrap(Policy.Timeout(2, TimeoutStrategy.Pessimistic));
                    policy.Execute(() =>
                    {
                        context.Response.WriteAsync("222");
                        Thread.Sleep(5000);
                        context.Response.WriteAsync("333");
                    });
                }
                catch
                {
                }
            });
        }