API网关后端微服务【免费下载链接】Ocelot.NET API Gateway项目地址https://gitcode.com/gh_mirrors/oc/Ocelot点击查看免费下载本文以仓库中的 samples/ServiceFabric/README.md 为核心骨架讲解如何把 Ocelot 作为 API 网关部署进 Service Fabric 集群网关通过命名服务Naming Service解析并访问集群内的下游服务。读完本文你将掌握 ServiceFabric 类型服务发现的配置方式、网关宿主与下游服务的 StatelessService 实现要点、应用打包与部署脚本的使用方法以及本地开发集群上的验证手段。文中所有配置、代码与路径均来自当前仓库可对照 samples/ServiceFabric 目录逐项验证。示例概述网关与下游服务如何在一个集群内协作该示例展示的是一个典型的 Service Fabric 集群拓扑Ocelot 网关OcelotApplicationApiGateway无状态服务对外暴露 HTTP 端口接收外部请求下游服务OcelotApplicationService无状态服务承载业务 API两者都作为同一个 Service Fabric 应用OcelotServiceApplication下的服务实例被调度和部署。Ocelot 不直接配置下游服务的固定地址而是通过 Service Fabric 的命名服务来“发现”目标服务——这正是 README 中 accessing services in the cluster via the naming service 的含义。从仓库结构看示例由三部分组成ApiGateway无状态服务宿主 Ocelot 网关本体Ocelot 的配置、中间件、服务发现逻辑都在这里DownstreamService无状态服务提供/api/values等 REST 接口作为被代理的下游OcelotApplicationService Fabric 应用打包目录包含两个服务的 ServiceManifest、入口脚本和全局 ApplicationManifest。README 也明确指出本示例假设读者对 Service Fabric 已有较好的理解This sample assumes a good understanding of Service Fabric并且作者只在Windows 开发集群上验证过未在 Linux 上的 Service Fabric 集群中测试过该示例——这两个前提在后续选型与排障时值得留意。Ocelot 网关配置详解ServiceFabric 类型服务发现示例网关的完整配置位于 samples/ServiceFabric/ApiGateway/ocelot.json内容如下{ Routes: [ { DownstreamScheme: http, DownstreamPathTemplate: /api/values, UpstreamPathTemplate: /EquipmentInterfaces, UpstreamHttpMethod: [ Get ], ServiceName: OcelotServiceApplication/OcelotApplicationService } ], GlobalConfiguration: { RequestIdKey: Oc-RequestId, ServiceDiscoveryProvider: { Host: localhost, Port: 19081, Type: ServiceFabric } } }这份配置体现了 Service Fabric 场景下 Ocelot 路由的两个关键点路由中不再写DownstreamHostAndPorts改用ServiceName。路由的目标以OcelotServiceApplication/OcelotApplicationService这种「应用名/服务名」格式给出与 ApplicationManifest.xml 中DefaultServices里定义的服务名OcelotApplicationService对应。全局配置中启用服务发现ServiceDiscoveryProvider.Type取值为ServiceFabricHost与Port指向命名服务地址示例中为localhost:19081即 Windows 开发集群上 Service Fabric 命名服务/反向代理默认的 HTTP 端口。源码印证ServiceFabricServiceDiscoveryProvider 的实现Ocelot 的核心库中src/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs 定义了Type ServiceFabric常量并实现了IServiceDiscoveryProviderpublic class ServiceFabricServiceDiscoveryProvider : IServiceDiscoveryProvider { public const string Type ServiceFabric; private readonly ServiceFabricConfiguration _configuration; public ServiceFabricServiceDiscoveryProvider(ServiceFabricConfiguration configuration) { _configuration configuration; } public TaskListService GetAsync() { return Task.FromResult(new ListService { new(_configuration.ServiceName, new ServiceHostAndPort(_configuration.HostName, _configuration.Port), doesnt matter with service fabric, doesnt matter with service fabric, new Liststring()), }); } }从源码结构可以推断该 Provider 将路由的ServiceName与全局配置中的Host/Port组合成唯一的Service返回代码注释 doesnt matter with service fabric 说明在 Service Fabric 场景下示例并不依赖 Ocelot 自己去解析出具体节点地址而是把集群内寻址交给 Service Fabric 自身命名服务/反向代理完成。其构造参数来自 src/ServiceDiscovery/Configuration/ServiceFabricConfiguration.cs持有HostName、Port、ServiceName三个字段。Provider 的装配逻辑在 src/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs工厂在路由开启服务发现后比较config.Type与ServiceFabricServiceDiscoveryProvider.Type忽略大小写匹配即用config.Host、config.Port与route.ServiceName构造ServiceFabricConfiguration不匹配则回退到自定义ServiceDiscoveryFinderDelegate仍找不到则返回UnableToFindServiceDiscoveryProviderError。这意味着只要把Type配成ServiceFabricOcelot 就会走这条固定链路无需额外注册委托。关于 Stateful Services 与 Reliable ActorsPartitionKind / PartitionKeyREADME 特别强调了一条使用约束If you want to use statefull / actors you must send the PartitionKind and PartitionKey to Ocelot as query string parameters.也就是说如果下游目标是有状态服务Stateful Service或 Reliable ActorsOcelot 需要通过查询字符串拿到PartitionKind与PartitionKey才能正确路由到对应分区。在当前示例中下游是无状态服务SingletonPartition因此未涉及这两个参数一旦你的路由目标是分区服务就必须在请求 URL 上携带它们否则网关无法确定请求应送往哪个分区副本。这是在 Service Fabric 场景下从示例可运行走向生产可用时最容易踩到的一个配置点。网关宿主实现如何把 Ocelot 跑进 StatelessService网关侧的核心不是 Startup 模板而是 Service Fabric 的通信监听器。WebCommunicationListener.cs 实现了ICommunicationListener其OpenAsync完成三件事从CodePackageActivationContext.GetEndpoint(WebEndpoint)取回清单里声明的端口即31002见下文 ServiceManifest拼出监听地址与发布地址_listeningAddress http://:{port}/...再把替换为节点 IP/FQDN 得到_publishAddress启动 ASP.NET Core 宿主并挂载 Ocelot 管道_ OcelotHostBuilder.Create(); var builder WebApplication.CreateBuilder(); builder.WebHost.UseUrls(_listeningAddress); builder.Configuration .SetBasePath(builder.Environment.ContentRootPath) .AddOcelot(); builder.Services .AddOcelot(builder.Configuration); if (builder.Environment.IsDevelopment()) { builder.Logging.AddConsole(); } _webApp builder.Build(); await _webApp.UseOcelot(); await _webApp.RunAsync();可以看到UseUrls绑定的是 Service Fabric 分配的端口而配置加载走的仍是 Ocelot 标准的AddOcelot()/UseOcelot()链路底层实现在 src/DependencyInjection。CloseAsync/Abort则统一收敛到StopAll对_webApp执行StopAsync保证服务实例被回收时 Web 宿主能优雅关闭。宿主进程入口 ApiGateway/Program.cs 负责注册服务类型var listener new ServiceEventListener(OcelotApplicationApiGateway); listener.EnableEvents(ServiceEventSource.Current, EventLevel.LogAlways, EventKeywords.All); await ServiceRuntime.RegisterServiceAsync(OcelotApplicationApiGatewayType, context new OcelotServiceWebService(context)); Thread.Sleep(Timeout.Infinite);OcelotServiceWebService见 OcelotApplicationApiGateway.cs继承StatelessService在CreateServiceInstanceListeners中注册名为OcelotServiceWebListener的监听器并绑定WebCommunicationListener。注册的服务类型名OcelotApplicationApiGatewayType必须与 ServiceManifest.xml 中StatelessServiceType ServiceTypeNameOcelotApplicationApiGatewayType /一致——这是 Service Fabric 运行时把实例映射到宿主进程的关键约定。此外ServiceEventListener/ServiceEventSource见 ServiceEventListener.cs 与 ServiceEventSource.cs把跟踪输出重定向到文件便于在无交互环境下排查问题。下游服务实现Kestrel 监听器与测试接口下游服务 DownstreamService/ApiGateway.cs 同样是无状态服务但它使用KestrelCommunicationListener并指定ServiceFabricIntegrationOptions.UseUniqueServiceUrl让 Service Fabric 为每个服务实例分配唯一的监听 URLnew KestrelCommunicationListener(serviceContext, ServiceEndpoint, (url, listener) { var builder WebApplication.CreateBuilder(); builder.Services .AddSingleton(serviceContext) .AddControllers(); builder.WebHost .UseContentRoot(Directory.GetCurrentDirectory()) .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl) .UseUrls(url); var app builder.Build(); app.MapControllers(); return app; })接口本体位于 DownstreamService/Controllers/ValuesController.csGET /api/values返回[value1,value2]并附带按 id 取值、POST/PUT/DELETE 的标准模板。这个GET /api/values正是ocelot.json中DownstreamPathTemplate的落点——外部请求/EquipmentInterfaces经 Ocelot 转发后变为下游的/api/values。Service Fabric 应用打包Manifest、端点与端口Ocelot 网关对外暴露的端口由清单声明。在 OcelotApplicationApiGatewayPkg/ServiceManifest.xml 中Resources Endpoints Endpoint NameWebEndpoint Protocolhttp Port31002 / /Endpoints /ResourcesWebEndpoint固定为 HTTP 端口31002与 WebCommunicationListener.cs 中GetEndpoint(WebEndpoint)的读取逻辑一一对应。下游服务的 ServiceManifest.xml 则声明ServiceEndpoint且未固定端口——端口由 Service Fabric 按UseUniqueServiceUrl动态分配。两个服务包由 ApplicationManifest.xml 统一编排ServiceManifestImport分别引用OcelotApplicationServicePkg与OcelotApplicationApiGatewayPkg版本均为 1.0.0DefaultServices定义两个无状态服务ServiceTypeName分别为OcelotApplicationServiceType与OcelotApplicationApiGatewayType并给出可覆盖参数OcelotApplicationService_InstanceCount/OcelotApplicationApiGateway_InstanceCount默认均为 1。此外代码包目录 OcelotApplicationApiGatewayPkg/Code 中的entryPoint.cmdWindows与entryPoint.shLinux是服务的进程入口。以 entryPoint.sh 为例它通过dotnet-include.sh兼容 RHEL 的 sclsoftware collectionsdotnet CLI最终执行dotnet $DIR/OcelotApplicationApiGateway.dll。构建、部署与卸载脚本README 中列出的目录/脚本约定如下该部分沿袭自 Microsoft 的 ASP.NET Core Service Fabric 入门指南application package folder/Service Fabric 应用包目录层次编译产物放入其下的code子目录build.sh/build.ps1Linux/Windows 下的源码构建脚本install.sh/install.ps1安装应用脚本Windows 侧调用前需先执行Connect-ServiceFabricCluster localhost:19000建立连接uninstall.sh/uninstall.ps1卸载应用脚本dotnet-include.sh用于条件处理 RHEL 上通过 scl 提供的 dotnet CLI。在仓库实际内容中install.sh 展示了完整的 Linux 部署链路先把ServiceManifest-Linux.xml复制为各服务包的ServiceManifest.xml平台差异通过 manifest 副本切换把dotnet-include.sh拷贝进两个代码包随后依次执行sfctl application upload --path OcelotServiceApplication --show-progress sfctl application provision --application-type-build-path OcelotServiceApplication sfctl application create --app-name fabric:/OcelotServiceApplication --app-type OcelotServiceApplicationType --app-version 1.0.0即上传应用包 → 注册应用类型 → 创建应用实例应用名fabric:/OcelotServiceApplication类型OcelotServiceApplicationType。Windows 侧对应的 PowerShell 版本见 install.ps1、uninstall.ps1 与 uninstall.sh。验证通过网关访问下游接口README 给出的验收标准非常明确在开发集群一切就绪后访问http://localhost:31002/EquipmentInterfaces应返回[value1,value2]这条链路完整串联了前面所有组件外部请求打到网关WebEndpoint31002→ Ocelot 按UpstreamPathTemplate: /EquipmentInterfaces匹配路由 → 依据ServiceName与 ServiceFabric 类型服务发现定位下游 → 转发到DownstreamPathTemplate: /api/values→ValuesController.Get()返回[value1,value2]。若返回异常README 建议先检查 Service Fabric 日志本示例中网关侧已通过ServiceEventListener将事件源输出重定向至文件再对照清单、端口与命名服务配置逐项排查。使用前提与注意事项开发环境前置条件是已安装 Service Fabric C# SDKLinux 开发环境的具体准备步骤可参考 README 中给出的官方入门指引链接。平台验证范围README 明确说明该示例仅在一个Windows 开发集群上测试过未覆盖 Linux 托管的 Service Fabric 集群跨平台使用时需自行验证。目标类型路由目标为无状态服务时无需额外参数若为Stateful Service / Reliable Actors必须在请求中携带PartitionKind与PartitionKey查询参数。命名服务地址GlobalConfiguration.ServiceDiscoveryProvider的Host/Port示例为localhost:19081指向集群命名服务地址应与实际集群保持一致。工程基线网关项目 Ocelot.Samples.ServiceFabric.ApiGateway.csproj 目标框架为net8.0;net9.0;net10.0引用Microsoft.ServiceFabric与Microsoft.ServiceFabric.Services包并通过ProjectReference直接引用 src/Ocelot.csproj 与 samples/Web/Ocelot.Samples.Web.csproj后者提供OcelotHostBuilder可作为自定义 Service Fabric 网关宿主的最小工程模板。小结该示例以最小可运行的形态演示了 Ocelot 与 Service Fabric 的集成范式网关与下游服务同处一个集群、以ServiceNameType: ServiceFabric完成服务发现、通过ICommunicationListener/KestrelCommunicationListener挂载 Ocelot 管道、以sfctl完成部署与验证。结合 src/ServiceDiscovery 的工厂与 Provider 源码可以看清配置 → 工厂装配 → Provider 返回 Service的完整调用链在此基础上无论是扩展到分区服务、多副本还是生产集群都可以从本示例出发做增量改造。赞分享API网关后端微服务【免费下载链接】Ocelot.NET API Gateway项目地址https://gitcode.com/gh_mirrors/oc/Ocelot点击查看免费下载相关推荐Ocelot Service Fabric 集成指南借助命名服务实现 Azure Service Fabric 服务代理Ocelot Service Fabric 集成指南借助命名服务实现 Azure Service Fabric 服务代理 导读 本文档系统讲解 OcelotAPI网关后端微服务gh_mirrors/gumr/gumroadAPI网关Kong集成与请求路由gh_mirrors/gumr/gumroadAPI网关Kong集成与请求路由 项目路由架构概述 gh_mirrors/gumr/gumroad项目采用Rai后端前端电商emilianJR/chilloutmix_NiPrunedFp32Fix无服务器部署云平台方案对比emilianJR/chilloutmix_NiPrunedFp32Fix无服务器部署云平台方案对比 emilianJR/chilloutmix_NiPrun基础模型计算机视觉大模型模型推理服务上一篇Redis 3.0并发控制技术基于注释版源码的锁机制实现下一篇Yuedu书源字体透明度与电池使用测试数据创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考