胡罡 發表於 2018-3-20 20:37:00

netcore 使用surging框架发布到docker

<p style="text-align: left"><span style="line-height: 1.5">demo运行在windows的docker中,系统是win10,所以需要先下载Docker for Windows,安装完毕后系统会重启,然后桌面上可以找到Docker for Windows的快捷图标,右下角有个鲸鱼小图标</span></p>
<p><span style="line-height: 1.5"><img style="float: left" src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320194545619-27724431.jpg" alt=""></span></p>
<p>&nbsp;</p>
<p><span style="line-height: 1.5">单击右键,选择菜单中的Kitematic</span></p>
<p><span style="line-height: 1.5"><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320194745775-1047406972.jpg" alt=""></span></p>
<p><span style="line-height: 1.5">会提示你下载Kitematic,自行下载后解压即可,将Kitematic快捷到桌面;</span></p>
<p><span style="line-height: 1.5">打开Kitematic,在搜索栏中下载好RabbitMQ、redis、consul相关镜像,因为这些是surging运行的先决条件。</span></p>
<p><span style="line-height: 1.5"><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320195210369-1026437142.png" alt=""></span></p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320195229169-1540600429.jpg" alt=""></p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320195245306-895608114.jpg" alt=""></p>
<p><span style="line-height: 1.5">接着去GitHub上下载surging网关项目,修改其中的gatewaySettings.json中Register下的Address地址,对应的事consul docker镜像的ip</span></p>
<p><span style="line-height: 1.5">具体如何查看其ip,看如下操作:</span></p>
<p><span style="line-height: 1.5">打开Kitematic,点击左下角,如图:</span></p>
<p><span style="line-height: 1.5"><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320195746164-328287673.jpg" alt=""></span></p>
<p>&nbsp;</p>
<p>进入到命令窗口,输入docker container ls或者 &nbsp;docker ps -a &nbsp;查看docker,</p>
<p>可以看到现在运行的docker的相关信息,</p>
<p>如图:</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320200156853-560818815.jpg" alt=""></p>
<p>然后查看consul的相关配置,输入docker inspect &nbsp;镜像的 containerID,如consul的id是b0e98b94638c,输入命令如下:docker inspect &nbsp;b0e98b94638c,</p>
<p>显示这个docker的配置,内容会很多,不过ip的信息在最后,如图</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320200434668-1543764019.jpg" alt=""></p>
<p>&nbsp;找到其中的ip是多少,然后修改surging网关中的consul地址为:"Address": "172.17.0.4:8500",其他配置根据上面的操作进行修改,如redis 镜像地址的查找和修改等;</p>
<p>修改好surging的网关配置后在Surging.ApiGateway项目上单击右键,由于我项目中已经添加过,所以该处为灰色,如图:</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320200813259-1444216588.jpg" alt=""></p>
<p>新建docker-Compose后修改其中docker-compose.yml的配置如下:</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320200943666-483023827.jpg" alt=""></p>
<p>在后面添加docker的外部端口和内部端口的映射和网络模式,这里我们都使用桥接模式,包括之前的consul、RabbitMQ、redis都是同一模式,这样他们会在同一VLAN下,</p>
<p>然后运行网关,如下:</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320201234370-1442801450.jpg" alt=""></p>
<p>接下来新建一个解决方案,方案名随意,喜欢就好,由于时间比较短,这里我简单的处理,不清楚的可以留言</p>
<p>新建Service.A,然后在其下新建控制台应用Service.A、Service.B、Service.C,新建类库Service.A.Service、Service.B.Service、Service.C.Service;</p>
<p>编辑Service.A.csporj、Service.B.csporj、Service.C.csporj,如下</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320201748014-1748435483.jpg" alt=""></p>
<p>将其中的引用包都复制过去,分别修改一下对应的Service,即其中的&lt;ProjectReference Include="..\Service.A.Service\Service.A.Service.csproj" /&gt;,Service.A引用Service.A.Service,Service.B引用Service.B.Service</p>
<p>Service.C引用Service.C.Service;</p>
<p>类库Service.A.Service、Service.B.Service、Service.C.Service中都引用</p>
<p>&lt;PackageReference Include="surging" Version="0.5.4" /&gt;</p>
<p>如图:</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320202104919-253346679.jpg" alt=""></p>
<p>&nbsp;</p>
<p>由于代码很多地方相识,以下我只说Service.A,和Service.A.Service;</p>
<p>Service.A 中新增Configs文件夹,下面添加log4net.config,log4net.config代码如下:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">&lt;log4net&gt;
&lt;root&gt;
    &lt;level value="Error" /&gt;
    &lt;!-- &lt;appender-ref ref="RollingLogFileAppender" /&gt; --&gt;
    &lt;appender-ref ref="ErrorRollingLogFileAppender" /&gt;
&lt;/root&gt;
&lt;appender name="ErrorRollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net" LEVEL="ERROR"&gt;
    &lt;lockingModel type="log4net.Appender.FileAppender+MinimalLock" /&gt;
    &lt;param name="File" value="c:\surging\Error\" /&gt;
    &lt;param name="AppendToFile" value="true" /&gt;
    &lt;param name="RollingStyle" value="Composite" /&gt;
    &lt;param name="DatePattern" value="_yyyyMMddHH.TXT" /&gt;
    &lt;param name="StaticLogFileName" value="false" /&gt;
    &lt;param name="MaxSizeRollBackups" value="-1" /&gt;
    &lt;param name="MaximumFileSize" value="5MB" /&gt;
    &lt;layout type="log4net.Layout.PatternLayout,log4net"&gt;
      &lt;param name="ConversionPattern" value="%date [%thread] %-5level %logger [%ndc] - %message%newline" /&gt;
    &lt;/layout&gt;
    &lt;filter type="log4net.Filter.LevelRangeFilter"&gt;
      &lt;param name="LevelMin" value="ERROR" /&gt;
      &lt;param name="LevelMax" value="FATAL" /&gt;
    &lt;/filter&gt;
&lt;/appender&gt;
&lt;/log4net&gt;
</pre>
</div>
<p>  </p>
<p>然后新增cacheSettings.json其中Map:Properties下的value的值是redis地址</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">{
    "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"
          }
      ]
      }
    ]
}
</pre>
</div>
<p>  </p>
<p>新增eventBusSettings.json,其中的EventBusConnection对应的是RabbitMQ docker的地址</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">{
"EventBusConnection": "172.17.0.3",
"EventBusUserName": "guest",
"EventBusPassword": "guest"
}
</pre>
</div>
<p>Program.cs的代码如下</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">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 =&gt;
                {
                  builder.AddMicroService(option =&gt;
                  {
                        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 =&gt; 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 =&gt;
                {
                  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&lt;Startup&gt;()
                .Build();

            using (host.Run())
            {
                Console.WriteLine($"服务端启动成功,{DateTime.Now}。");
            }
      }
    }
}
</pre>
</div>
<p>  新增Startup.cs</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">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&lt;ILoggerFactory&gt;()
                  .AddConsole((c, l) =&gt; (int)l &gt;= 3);
      }

      #region 私有方法
      /// &lt;summary&gt;
      /// 配置日志服务
      /// &lt;/summary&gt;
      /// &lt;param name="services"&gt;&lt;/param&gt;
      private void ConfigureLogging(IServiceCollection services)
      {
            services.AddLogging();
      }

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

      /// &lt;summary&gt;
      /// 配置缓存服务
      /// &lt;/summary&gt;
      private void ConfigureCache(IConfigurationBuilder build)
      {
            build
            .AddCacheFile("cacheSettings.json", optional: false);
      }
      #endregion

    }
}
</pre>
</div>
<p>  Service.A.Service 类库下新增AService.cs</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">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&lt;string&gt; SayHello(string name)
      {
            return Task.FromResult($"{name} say : hello");
      }
    }
}
</pre>
</div>
<p>  </p>
<p>&nbsp;新增IAService.cs</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">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
{
   
    public interface IAService : IServiceKey
    {
      Task&lt;string&gt; SayHello(string name);
    }
}
</pre>
</div>
<p>  其他类库和服务与以上代码基本无二,这里不在赘述。不清楚的可以留言</p>
<p>&nbsp;</p>
<p>所有代码都处理好后,在Service.A、Service.B、Service.C项目上右键新增docker支持文件,然后会生成一下文件</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320203024832-386228127.jpg" alt=""></p>
<p>&nbsp;修改其中的docker-compose.yml</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">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
</pre>
</div>
<p>  然后选择docker运行即可</p>
<p>最后访问surging网关,即可看见效果</p>
<p><img src="https://images2018.cnblogs.com/blog/454803/201803/454803-20180320203550133-1991397412.png" alt=""></p>

</div>
<div id="MySignature" role="contentinfo">
    吾日三省吾身<br><br>
来源:https://www.cnblogs.com/landonzeng/p/8612026.html
頁: [1]
查看完整版本: netcore 使用surging框架发布到docker