netcore 使用surging框架發佈到docker

demo運行在windows的docker中,系統是win10,因此須要先下載Docker for Windows,安裝完畢後系統會重啓,而後桌面上能夠找到Docker for Windows的快捷圖標,右下角有個鯨魚小圖標web

 

單擊右鍵,選擇菜單中的Kitematicredis

會提示你下載Kitematic,自行下載後解壓便可,將Kitematic快捷到桌面;docker

打開Kitematic,在搜索欄中下載好RabbitMQ、redis、consul相關鏡像,由於這些是surging運行的先決條件。json

接着去GitHub上下載surging網關項目,修改其中的gatewaySettings.json中Register下的Address地址,對應的事consul docker鏡像的ipwindows

具體如何查看其ip,看以下操做:api

打開Kitematic,點擊左下角,如圖:緩存

 

進入到命令窗口,輸入docker container ls或者  docker ps -a  查看docker,網絡

能夠看到如今運行的docker的相關信息,app

如圖:webapp

而後查看consul的相關配置,輸入docker inspect  鏡像的 containerID,如consul的id是b0e98b94638c,輸入命令以下:docker inspect  b0e98b94638c,

顯示這個docker的配置,內容會不少,不過ip的信息在最後,如圖

 找到其中的ip是多少,而後修改surging網關中的consul地址爲:"Address": "172.17.0.4:8500",其餘配置根據上面的操做進行修改,如redis 鏡像地址的查找和修改等;

修改好surging的網關配置後在Surging.ApiGateway項目上單擊右鍵,因爲我項目中已經添加過,因此該處爲灰色,如圖:

新建docker-Compose後修改其中docker-compose.yml的配置以下:

在後面添加docker的外部端口和內部端口的映射和網絡模式,這裏咱們都使用橋接模式,包括以前的consul、RabbitMQ、redis都是同一模式,這樣他們會在同一VLAN下,

而後運行網關,以下:

接下來新建一個解決方案,方案名隨意,喜歡就好,因爲時間比較短,這裏我簡單的處理,不清楚的能夠留言

新建Service.A,而後在其下新建控制檯應用Service.A、Service.B、Service.C,新建類庫Service.A.Service、Service.B.Service、Service.C.Service;

編輯Service.A.csporj、Service.B.csporj、Service.C.csporj,以下

將其中的引用包都複製過去,分別修改一下對應的Service,即其中的<ProjectReference Include="..\Service.A.Service\Service.A.Service.csproj" />,Service.A引用Service.A.Service,Service.B引用Service.B.Service

Service.C引用Service.C.Service;

類庫Service.A.Service、Service.B.Service、Service.C.Service中都引用

<PackageReference Include="surging" Version="0.5.4" />

如圖:

 

因爲代碼不少地方相識,如下我只說Service.A,和Service.A.Service;

Service.A 中新增Configs文件夾,下面添加log4net.config,log4net.config代碼以下:

<log4net>
  <root>
    <level value="Error" />
    <!-- <appender-ref ref="RollingLogFileAppender" /> -->
    <appender-ref ref="ErrorRollingLogFileAppender" />
  </root>
  <appender name="ErrorRollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net" LEVEL="ERROR">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <param name="File" value="c:\surging\Error\" />
    <param name="AppendToFile" value="true" />
    <param name="RollingStyle" value="Composite" />
    <param name="DatePattern" value="_yyyyMMddHH.TXT" />
    <param name="StaticLogFileName" value="false" />
    <param name="MaxSizeRollBackups" value="-1" />
    <param name="MaximumFileSize" value="5MB" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
      <param name="LevelMin" value="ERROR" />
      <param name="LevelMax" value="FATAL" />
    </filter>
  </appender>
</log4net>

  

而後新增cacheSettings.json其中Map:Properties下的value的值是redis地址

{ 
    "CachingSettings": [
      {
        "Id": "ddlCache",
        "Class": "Surging.Core.Caching.RedisCache.RedisContext,Surging.Core.Caching",
        "Properties": [
          {
            "Name": "appRuleFile",
            "Ref": "rule"
          },
          {
            "Name": "dataContextPool",
            "Ref": "ddls_sample",
            "Maps": [
              {
                "Name": "Redis",
                "Properties": [
                  {
                    "value": "172.17.0.2:6379::1"
                  }
                ]
              },
              {
                "Name": "MemoryCache"
              }
            ]
          },
          {
            "Name": "defaultExpireTime",
            "value": "120"
          },
          {
            "Name": "connectTimeout",
            "Value": "120"
          },
          {
            "Name": "minSize",
            "Value": "1"
          },
          {
            "Name": "maxSize",
            "Value": "10"
          }
        ]
      }
    ]
}

  

新增eventBusSettings.json,其中的EventBusConnection對應的是RabbitMQ docker的地址

{
  "EventBusConnection": "172.17.0.3",
  "EventBusUserName": "guest",
  "EventBusPassword": "guest"
}

Program.cs的代碼以下

using Autofac;
using Surging.Core.Codec.MessagePack;
using Surging.Core.Consul;
using Surging.Core.Consul.Configurations;
using Surging.Core.CPlatform;
using Surging.Core.CPlatform.Utilities;
using Surging.Core.DotNetty;
using Surging.Core.EventBusRabbitMQ;
using Surging.Core.Log4net;
using Surging.Core.ProxyGenerator;
using Surging.Core.ServiceHosting;
using Surging.Core.ServiceHosting.Internal.Implementation;
using System;
using System.Text;

namespace Service.A
{
    class Program
    {
        static void Main(string[] args)
        {
            NewMethod();
        }

        private static void NewMethod()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var host = new ServiceHostBuilder()
                .RegisterServices(builder =>
                {
                    builder.AddMicroService(option =>
                    {
                        option.AddServiceRuntime();
                        option.AddRelateService();
                        //option.UseZooKeeperManager(new ConfigInfo("127.0.0.1:2181"));
                        option.UseConsulManager(new ConfigInfo("172.17.0.4:8500"));
                        option.UseDotNettyTransport();
                        option.UseRabbitMQTransport();
                        option.AddRabbitMQAdapt();
                        //option.UseProtoBufferCodec();
                        option.UseMessagePackCodec();
                        builder.Register(p => new CPlatformContainer(ServiceLocator.Current));
                    });
                })
                .SubscribeAt()
                .UseLog4net("Configs/log4net.config")
                //.UseServer("127.0.0.1", 98)
                //.UseServer("127.0.0.1", 98,「true」) //自動生成Token
                //.UseServer("127.0.0.1", 98,「123456789」) //固定密碼Token
                .UseServer(options =>
                {
                    options.Ip = "172.17.0.6";
                    options.Port = 9990;
                    options.Token = "True";
                    options.ExecutionTimeoutInMilliseconds = 30000;
                    options.MaxConcurrentRequests = 200;
                    options.NotRelatedAssemblyFiles = "Centa.Agency.Application.DTO\\w*|StackExchange.Redis\\w*";
                })
                .UseProxy()
                .UseStartup<Startup>()
                .Build();

            using (host.Run())
            {
                Console.WriteLine($"服務端啓動成功,{DateTime.Now}。");
            }
        }
    }
}

  新增Startup.cs

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Surging.Core.Caching.Configurations;
using Surging.Core.CPlatform.Utilities;
using Surging.Core.EventBusRabbitMQ.Configurations;
using System;

namespace Service.A
{
    public class Startup
    {
        public Startup()
        {
            var config = new ConfigurationBuilder()
           .SetBasePath(AppContext.BaseDirectory);
            ConfigureEventBus(config);
            //ConfigureCache(config);
        }

        public IContainer ConfigureServices(ContainerBuilder builder)
        {
            var services = new ServiceCollection();
            ConfigureLogging(services);
            builder.Populate(services);
            ServiceLocator.Current = builder.Build();
            return ServiceLocator.Current;
        }

        public void Configure(IContainer app)
        {
            app.Resolve<ILoggerFactory>()
                    .AddConsole((c, l) => (int)l >= 3);
        }

        #region 私有方法
        /// <summary>
        /// 配置日誌服務
        /// </summary>
        /// <param name="services"></param>
        private void ConfigureLogging(IServiceCollection services)
        {
            services.AddLogging();
        }

        private static void ConfigureEventBus(IConfigurationBuilder build)
        {
            build
            .AddEventBusFile("eventBusSettings.json", optional: false);
        }

        /// <summary>
        /// 配置緩存服務
        /// </summary>
        private void ConfigureCache(IConfigurationBuilder build)
        {
            build
              .AddCacheFile("cacheSettings.json", optional: false);
        }
        #endregion

    }
}

  Service.A.Service 類庫下新增AService.cs

using Surging.Core.ProxyGenerator;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Service.A.Service
{
    public class AService:ProxyServiceBase,IAService
    {
        public Task<string> SayHello(string name)
        {
            return Task.FromResult($"{name} say : hello");
        }
    }
}

  

 新增IAService.cs

using Surging.Core.CPlatform.Ioc;
using Surging.Core.CPlatform.Runtime.Server.Implementation.ServiceDiscovery.Attributes;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Service.A.Service
{
    [ServiceBundle("api/{Service}")]
    public interface IAService : IServiceKey
    {
        Task<string> SayHello(string name);
    }
}

  其餘類庫和服務與以上代碼基本無二,這裏不在贅述。不清楚的能夠留言

 

全部代碼都處理好後,在Service.A、Service.B、Service.C項目上右鍵新增docker支持文件,而後會生成一下文件

 修改其中的docker-compose.yml

version: '3'

services:
  service.a:
    image: servicea
    ports:
      - "127.0.0.1:9990:9990"
    network_mode: "bridge"
    build:
      context: .
      dockerfile: Service.A/Dockerfile

  service.b:
    image: serviceb
    ports:
      - "127.0.0.1:9991:9991"
    network_mode: "bridge"
    build:
      context: .
      dockerfile: Service.B/Dockerfile

  service.c:
    image: servicec
    ports:
      - "127.0.0.1:9992:9992"
    network_mode: "bridge"
    build:
      context: .
      dockerfile: Service.C/Dockerfile

  webapplication1:
    image: webapplication1
    build:
      context: .
      dockerfile: ../WebApplication1/Dockerfile

  而後選擇docker運行便可

最後訪問surging網關,便可看見效果

相關文章
相關標籤/搜索