demo 运行在 windows 的 docker 中, 系统是 win10, 所以需要先下载 Docker for Windows, 安装完毕后系统会重启, 然后桌面上可以找到 Docker for Windows 的快捷图标, 右下角有个鲸鱼小图标
单击右键, 选择菜单中的 Kitematic
会提示你下载 Kitematic, 自行下载后解压即可, 将 Kitematic 快捷到桌面;
打开 Kitematic, 在搜索栏中下载好 RabbitMQredisconsul 相关镜像, 因为这些是 surging 运行的先决条件
接着去 GitHub 上下载 surging 网关项目, 修改其中的 gatewaySettings.json 中 Register 下的 Address 地址, 对应的事 consul docker 镜像的 ip
具体如何查看其 ip, 看如下操作:
打开 Kitematic, 点击左下角, 如图:
进入到命令窗口, 输入 docker container ls 或者 docker ps -a 查看 docker,
可以看到现在运行的 docker 的相关信息,
如图:
然后查看 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 的外部端口和内部端口的映射和网络模式, 这里我们都使用桥接模式, 包括之前的 consulRabbitMQredis 都是同一模式, 这样他们会在同一 VLAN 下,
然后运行网关, 如下:
接下来新建一个解决方案, 方案名随意, 喜欢就好, 由于时间比较短, 这里我简单的处理, 不清楚的可以留言
新建 Service.A, 然后在其下新建控制台应用 Service.AService.BService.C, 新建类库 Service.A.ServiceService.B.ServiceService.C.Service;
编辑 Service.A.csporjService.B.csporjService.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.ServiceService.B.ServiceService.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.AService.BService.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 网关, 即可看见效果
来源: https://www.cnblogs.com/landonzeng/p/8612026.html