微服务~Eureka实现的服务注册与发现及服务之间的调用
2017-09-27

微服务里一个重要的概念就是服务注册与发现技术,当你有一个新的服务运行后,我们的服务中心可以感知你,然后把加添加到服务列表里,然后当你死掉后,会从服务中心把你移除,而你作为一个服务,对其它服务公开的只是服务名称,而不是最终的服务地址URL,这对于云平台,容器化架构来说是非常重要的!

  1. 安装单独的Eureka服务(server)
  2. 服务注册-aspnetcore建立Eureka客户端(client)
  3. 服务发现-实现服务与服务的调用

一 安装单独的Eureka服务

  1. 安装tomcat,到apache官网http://tomcat.apache.org  下载tomcat
  2. 下载Eureka,可以到http://mvnrepository.com/artifact/com.netflix.eureka/eureka-server  选择一下版本下载
  3. 配置端口,默认是8080,tomcat\webapps\eureka\WEB-INF\classes\eureka-client.properties
  4. 重启tomcat服务即可

二 aspnetcore建立Eureka客户端(client)

  1. nuget添加包包Pivotal.Discovery.Client
  2. 在startup.cs里添加客户端的自动发现代码(相对于eureka是客户端,事实上它是微服务里的一种服务)
  3. program里添加对某个端口的监听
  4. 将EurekaServer的地址添加到appsettings里
  5. 启动项目,然后去服务中心查看自己的新服务

在startup.cs里

 

       public void ConfigureServices(IServiceCollection services)
        {
            services.AddDiscoveryClient(Configuration);
            services.AddMvc();
        }        // 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.UseDiscoveryClient();
        }

 

program里添加对某个端口的监听

 public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseUrls("http://*:8010")
                .Build();

将EurekaServer的地址添加到appsettings里,其中8010是自己监听的端口,Order是自己的名称


 "spring": {   
  "application": {    
    "name": "Order"
    }
  },  "eureka": {   
   "client": {     
    "serviceUrl": "http://localhost:8080/eureka/V2/",   
       "shouldFetchRegistry": false,    
         "shouldRegisterWithEureka": true
    },   
     "instance": {   
        "port": 8010
    }

然后启动项目,在你的服务中心就可以看到新加的服务了(http://localhost:8080/eureka/),这就是服务的注册!

三 服务发现-实现服务与服务的调用

我们在某个微服务的项目里,可以调用其它的服务,这类似于一种请求链的过程,以后我们讲spring cloud里会说其它相关的技术

       [HttpGet]      
       public IEnumerable<string> Get()
       {
            DiscoveryClient _discoveryClient = new DiscoveryClient(new EurekaClientConfig
            {
                EurekaServerServiceUrls = "http://localhost:8080/eureka/V2/",
                ProxyHost = "http://localhost:8080/eureka/V2/",
                ProxyPort = 8080,

            });            //得到服务中心所有服务和它的Url地址
            foreach (var item in _discoveryClient.Applications.GetRegisteredApplications())        
                  yield return $"{item.Name}={item.Instances.FirstOrDefault().HomePageUrl}";
        }

页面显示的结果中我们看到了所有的服务,它的名称和它的URL,这种URL在容器化部署里是动态的,所以我们不能像原来那样,把它写死了,这也就是服务发现产生的原因!

好了,今天对于服务注册与服务发现就说到这里,都是比较实干的东西!

原文地址: http://www.cnblogs.com/lori/p/7598058.html