Ocelot网关主地址不可用时切换至备用地址是否可行?
Absolutely, this failover scenario is fully supported by Ocelot! Your initial configuration is already on the right track—let me walk you through how to refine it to ensure seamless automatic switching.
How your current setup lays the groundwork
Your config correctly defines multiple downstream hosts and ports in DownstreamHostAndPorts, which is the first step to enabling failover. Ocelot is designed to handle multiple backend nodes, but we need to add a few more settings to make it detect unavailability and switch automatically.
Add load balancing & circuit breaker configuration
To get automatic failover, you’ll want to add load balancer settings and quality of service (QoS)/circuit breaker rules to your route. Here’s how to update your configuration:
{ "Routes": [ { "DownstreamPathTemplate": "/catalog", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 7001 }, { "Host": "localhost", "Port": 7002 } ], "UpstreamPathTemplate": "/catalog-api", // Add these settings for failover "LoadBalancerOptions": { "Type": "LeastConnection" // Prioritizes nodes with fewer active connections; "RoundRobin" works too }, "QoSOptions": { "ExceptionsAllowedBeforeBreaking": 3, // Number of failed requests before marking node as down "DurationOfBreak": 10000, // Time (ms) to avoid the failed node "TimeoutValue": 5000 // Time (ms) before a request is considered timed out } } ], "GlobalConfiguration": { "BaseUrl": "http://localhost:7000" } }
What this does
- Load Balancer: The
LeastConnectiontype helps distribute traffic smartly, but evenRoundRobinwill work for failover—it’s more about how Ocelot handles failed nodes. - Circuit Breaker: The
QoSOptionstell Ocelot to:- Count failed requests/timeouts to a node
- After 3 consecutive failures, "break" the circuit and stop sending traffic to that node for 10 seconds
- Automatically try reconnecting after the break duration—if the node is back online, it’ll be added back to the pool
Key behavior to expect
When your primary server (localhost:7001) goes offline:
- Ocelot will attempt requests to it, but after 3 failures (or timeouts), it’ll stop sending traffic there for 10 seconds
- All subsequent requests will automatically route to the backup server (localhost:7002)
- Once the primary server comes back online, Ocelot will start sending traffic to it again after the
DurationOfBreakperiod ends
This setup ensures your gateway stays resilient to backend outages with zero manual intervention.
内容的提问来源于stack exchange,提问作者Marcin Słotwiński

