Ocelot 开源项目使用教程

Ocelot 开源项目使用教程

Ocelot.NET API Gateway项目地址:https://gitcode.com/gh_mirrors/oc/Ocelot

1. 项目的目录结构及介绍

Ocelot 是一个基于 ASP.NET Core 的 API 网关项目,其目录结构清晰,便于理解和使用。以下是主要的目录结构及其介绍:

Ocelot/
├── src/
│   ├── Ocelot/
│   │   ├── Configuration/
│   │   ├── DownstreamRouteFinder/
│   │   ├── Errors/
│   │   ├── Logging/
│   │   ├── Middleware/
│   │   ├── Multiplexer/
│   │   ├── RateLimit/
│   │   ├── Requester/
│   │   ├── ResponseProcessor/
│   │   ├── Security/
│   │   ├── Swagger/
│   │   ├── Utilities/
│   │   ├── OcelotBuilder.cs
│   │   ├── OcelotMiddlewareExtensions.cs
│   │   ├── OcelotPipelineConfiguration.cs
│   │   ├── OcelotPipelineExtensions.cs
│   │   ├── OcelotOptions.cs
│   │   ├── OcelotRequestDelegateFactory.cs
│   │   ├── OcelotServiceCollectionExtensions.cs
│   │   ├── Program.cs
│   │   ├── Startup.cs
│   ├── Ocelot.Administration/
│   ├── Ocelot.Cache.CacheManager/
│   ├── Ocelot.Cache.Microsoft/
│   ├── Ocelot.DependencyInjection/
│   ├── Ocelot.Provider.Eureka/
│   ├── Ocelot.Provider.Polly/
│   ├── Ocelot.Requester.Middleware/
│   ├── Ocelot.Tracing.Butterfly/
│   ├── Ocelot.Tracing.OpenTracing/
├── test/
│   ├── Ocelot.AcceptanceTests/
│   ├── Ocelot.UnitTests/
├── README.md
├── LICENSE
├── .gitignore

主要目录介绍:

  • src/Ocelot/: 核心代码目录,包含配置、路由、中间件、限流、请求处理等多个模块。
  • src/Ocelot.Administration/: 管理模块,提供管理接口。
  • src/Ocelot.Cache.CacheManager/src/Ocelot.Cache.Microsoft/: 缓存实现模块。
  • src/Ocelot.DependencyInjection/: 依赖注入模块。
  • src/Ocelot.Provider.Eureka/src/Ocelot.Provider.Polly/: 服务发现和熔断器提供者。
  • src/Ocelot.Requester.Middleware/: 请求中间件。
  • src/Ocelot.Tracing.Butterfly/src/Ocelot.Tracing.OpenTracing/: 分布式追踪模块。
  • test/: 测试代码目录,包含单元测试和验收测试。

2. 项目的启动文件介绍

Ocelot 项目的启动文件主要位于 src/Ocelot/ 目录下,包括 Program.csStartup.cs

Program.cs

Program.cs 文件是 ASP.NET Core 应用程序的入口点,负责配置和启动 Web 主机。

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Startup.cs

Startup.cs 文件负责配置应用程序的服务和请求处理管道。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOcelot();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseOcelot().Wait();
    }
}

3. 项目的配置文件介绍

Ocelot 的配置文件通常是一个 JSON 文件,名为 ocelot.json,位于项目的根目录或配置目录中。

ocelot.json

Ocelot.NET API Gateway项目地址:https://gitcode.com/gh_mirrors/oc/Ocelot

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个在Ocelot中使用AddDelegatingHandler处理超时异常的示例: 1. 在Ocelot配置文件中添加以下代码: ``` { "ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5001 } ], "UpstreamPathTemplate": "/api/{everything}", "UpstreamHttpMethod": [ "Get" ], "Timeout": 5000, //设置超时时间 "DelegatingHandlers": [ "CustomDelegatingHandler" ] } ], "GlobalConfiguration": { "BaseUrl": "http://localhost:5000", "DelegatingHandlers": [ "CustomDelegatingHandler" ] } } ``` 上述代码中,我们在一个ReRoutes配置项中定义了一个超时时间为5秒的路由,并将CustomDelegatingHandler添加到DelegatingHandlers列表中。我们还在GlobalConfiguration中添加了CustomDelegatingHandler,以便在所有路由中使用。 2. 创建一个CustomDelegatingHandler类,代码如下: ``` using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Ocelot.Logging; public class CustomDelegatingHandler : DelegatingHandler { private readonly int _timeout; private readonly IOcelotLogger _logger; public CustomDelegatingHandler(int timeout, IOcelotLoggerFactory loggerFactory) { _timeout = timeout; _logger = loggerFactory.CreateLogger<CustomDelegatingHandler>(); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { using (var cts = new CancellationTokenSource()) { var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token); linkedCts.CancelAfter(_timeout); try { return await base.SendAsync(request, linkedCts.Token); } catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested && !cts.IsCancellationRequested) { _logger.LogWarning($"Request timed out after {_timeout} ms: {request.Method} {request.RequestUri}"); return new HttpResponseMessage(System.Net.HttpStatusCode.RequestTimeout); } } } } ``` 上述代码中,我们定义了一个名为CustomDelegatingHandler的DelegatingHandler类,它接收一个超时时间参数timeout和一个IOcelotLoggerFactory对象来记录日志。在SendAsync方法中,我们使用CancellationTokenSource和linkedCts来设置请求的超时时间,并在请求超时时返回一个带有RequestTimeout状态代码的错误响应。我们还使用OcelotLogger记录了超时日志信息。 3. 在Startup.cs文件中通过以下代码注册CustomDelegatingHandler: ``` public void ConfigureServices(IServiceCollection services) { services.AddOcelot() .AddDelegatingHandler<CustomDelegatingHandler>(true); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseOcelot().Wait(); } ``` 上述代码中,我们使用AddDelegatingHandler方法将CustomDelegatingHandler注册到Ocelot中,并设置shouldThrow属性为true,以便在DelegatingHandler中发生异常时,抛出异常。 这样,我们就可以在Ocelot中使用CustomDelegatingHandler处理超时异常了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花化贵Ferdinand

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值