1. 程式人生 > >.net framework 4.5 +steeltoe+ springcloud(一) 實現服務註冊功能

.net framework 4.5 +steeltoe+ springcloud(一) 實現服務註冊功能

首先得先了解並熟悉一下springcloud,並手動去搭建一個服務中心,也可參照eurake官方示例

如果是.net core的話,實現註冊也是沒有問題的,網上教程很多,可自行度娘。

最難的就是基於Framework的專案怎麼實現註冊,跟core的實現方式區別還是蠻大的,研究過程中也有不少坑。

下面就分享一下我踩完坑之後初步總結的實現步驟:

1.用VS2017或者其他建立NF4.5+的webAPI專案(webAPI的結構基本是保持MVC一致的,所以MVC專案基本也能按這個步驟來的)

2.在專案根目錄內新建檔案appsettings.json(這個檔案主要是配置服務中心eurke地址等資訊的):

{
  "spring": {
    "application": {
      "name": "demoService"
    }
  },
  "eureka": {
    "client": {
      "serviceUrl": "http://localhost:8761/eureka/",//服務中心地址
      "shouldFetchRegistry": false,
      "shouldRegisterWithEureka": true,//是否允許註冊到服務中心
 
 
      "validate_certificates": false
    },
    "instance": {
      "port": 3001
   
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "Pivotal": "Debug",
      "Steeltoe": "Debug"
    }
  }
}

3.在專案資料夾App_Start下建立ApplicationConfig.cs:

public static class ApplicationConfig
    {
​
        public static IConfigurationRoot Configuration { get; set; }
​
        public static void RegisterConfig(string environment)
        {
 
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(GetContentRoot())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                .AddJsonFile($"appsettings.{environment}.json", optional: true)
                .AddCloudFoundry()
                .AddEnvironmentVariables();
​
            Configuration = builder.Build();
        }
​
        public static string GetContentRoot()
        {
            var basePath = (string)AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ??
               AppDomain.CurrentDomain.BaseDirectory;
            return Path.GetFullPath(basePath);
        }
    }

注意這裡需要新增的引用:

using Microsoft.Extensions.Configuration;
using Steeltoe.Extensions.Configuration.CloudFoundry;

這兩個是需要在引用點右鍵選擇NuGet程式包裡新增的。

4.修改Global.asax檔案,在Application_Start()內加入程式碼:

GlobalConfiguration.Configure(WebApiConfig.Register);
​
 var config = GlobalConfiguration.Configuration;
​
// Build application configuration
 ApplicationConfig.RegisterConfig("development");
​
 var builder = new ContainerBuilder();
​
// Add Microsoft Options to container
  builder.RegisterOptions();
​
// Add Microsoft Logging to container
  builder.RegisterLogging(ApplicationConfig.Configuration);
​
// Add Console logger to container
  builder.RegisterConsoleLogging();
​
// Register your Web API controllers.
  builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
​
// Register IDiscoveryClient, etc.
  builder.RegisterDiscoveryClient(ApplicationConfig.Configuration);
​
// Initialize and Register FortuneContext
  builder.RegisterInstance(SampleData.InitializeFortunes()).SingleInstance();
​
// Register FortuneRepository
  builder.RegisterType<FortuneRepository>().As<IFortuneRepository>().SingleInstance();
​
  var container = builder.Build();
  config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
​
// Get a logger from container
  var logger = container.Resolve <ILogger<WebApiApplication>>();
​
  logger.LogInformation("Finished container build, starting background services");
​
// Start the Discovery client background thread
  container.StartDiscoveryClient();
​
  logger.LogInformation("Finished starting background services");

新增引用:

using Autofac;
using Autofac.Integration.WebApi;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Pivotal.Discovery.Client;
using Steeltoe.Common.Discovery;
using Steeltoe.Common.Logging.Autofac;
using Steeltoe.Common.Options.Autofac;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Web.Http;