0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · 课时

为熔断器添加降级方案

了解如何将熔断器与降级逻辑结合起来,使熔断器打开时服务能够平稳降级,而不是让用户请求直接失败。

为熔断器添加降级方案 是 CoddyKit 上的免费 Microservices Communication Patterns (Saga, Circuit Breaker) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Microservices Communication Patterns (Saga, Circuit Breaker) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Fallbacks Matter

A circuit breaker protects your service by failing fast when a dependency is down. But failing fast still means the user gets an error unless you provide a fallback.

A fallback is the plan B that runs when the breaker is open.

The Fallback Contract

A fallback should return a sensible default quickly and never call the same failing dependency. It is invoked when:

  • The breaker is open, or
  • The protected call throws or times out.

A Simple Fallback

Here is the core idea: try the real call, and if it fails, return the fallback value.

def get_price(call_remote):
    try:
        return call_remote()
    except Exception:
        return 'fallback: last-known price'

print(get_price(lambda: (_ for _ in ()).throw(Exception('down'))))

Fallback: Cached Value

A common strategy is to serve the last successful response from a cache. The user sees slightly stale data instead of an error.

cache = {'price': 42}

def get_with_cache(breaker_open):
    if breaker_open:
        return cache.get('price', 'unavailable')
    return 'fresh value'

print(get_with_cache(True))

Fallback: Default Value

When no cache exists, return a safe default: an empty list, a neutral recommendation, or a generic message. The key is that the user experience degrades, not breaks.

def recommendations(breaker_open):
    if breaker_open:
        return ['Popular item A', 'Popular item B']
    return ['Personalized 1', 'Personalized 2']

print(recommendations(True))

Fallback: Alternate Service

Sometimes plan B is another provider. If the primary payment gateway's breaker is open, route to a secondary gateway. Each provider has its own breaker.

Wiring Fallbacks in Resilience4j

Most libraries let you attach a fallback declaratively. With Resilience4j you decorate the call with a circuit breaker and supply a recover function that runs on failure or open state.

Keep Fallbacks Fast and Safe

A fallback must not introduce new failure modes:

  • No call to the broken dependency.
  • No blocking I/O that could also hang.
  • Bounded, predictable execution time.

Communicating Degradation

Tell the user (and your dashboards) when degraded data is served. A subtle UI note like 'showing cached results' sets expectations, and a metric on fallback rate reveals dependency health.

fallback_count = 0

def record_fallback():
    global fallback_count
    fallback_count += 1
    return fallback_count

print('Fallbacks served:', record_fallback())

When NOT to Fall Back

Some operations have no safe default. You cannot 'fall back' on confirming a payment. In those cases, fail clearly and let the caller retry later rather than fabricate a result.

Testing Fallbacks

Write tests that force the breaker open and assert the fallback runs and returns the expected safe value. Fallbacks that are never tested tend to break silently.

Quick Check

Which of these is a valid requirement for a circuit breaker fallback?

Recap

You learned to add fallbacks to circuit breakers:

  • Fallbacks run when the breaker is open or the call fails.
  • Common strategies: cached value, safe default, alternate service.
  • Keep fallbacks fast, safe, and free of the broken dependency.
  • Communicate degradation and test fallbacks explicitly.

Fallbacks turn fast failures into graceful degradation.

常见问题解答

「为熔断器添加降级方案」课时是免费的吗?

是的 — 「为熔断器添加降级方案」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Microservices Communication Patterns (Saga, Circuit Breaker) 课程的其余内容,请升级到 CoddyKit PRO。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。

「为熔断器添加降级方案」这节课中我会学到什么?

了解如何将熔断器与降级逻辑结合起来,使熔断器打开时服务能够平稳降级,而不是让用户请求直接失败。 你通过在浏览器中直接运行的动手代码来练习 Microservices Communication Patterns (Saga, Circuit Breaker),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Microservices Communication Patterns (Saga, Circuit Breaker) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Microservices Communication Patterns (Saga, Circuit Breaker) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「为熔断器添加降级方案」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Microservices Communication Patterns (Saga, Circuit Breaker) 课中编写并运行代码吗?

能。每节 Microservices Communication Patterns (Saga, Circuit Breaker) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 选择熔断器库
  2. 配置熔断器实例
  3. 集成到服务调用中
  4. 为熔断器添加降级方案
← 返回 Microservices Communication Patterns (Saga, Circuit Breaker)