5.2. 使用 circuit breaker 事件的事件处理程序的示例应用


本例演示了如何侦听断路器发出的不同事件类型。在本例中,使用 fetch 函数来请求微服务 URL。根据事件类型,相关消息会输出到 web 控制台。

...

// Import the circuit breaker add-on
const Opossum = require('@redhat/opossum');

...

// Create a new circuit breaker instance and pass the
// protected function call as its first parameter
const circuit = new Opossum(() => $.get(route), circuitOptions);

...

// Listen for success events emitted when the
// circuit breaker action completes successfully
circuit.on('success',
  (result) => {
    console.log(`SUCCESS: ${JSON.stringify(result)}`);
  }

// Listen for timeout events emitted when the timeout
// period for the circuit breaker action expires
circuit.on('timeout',
  (result) => {
    console.log(`TIMEOUT: ${url} is taking too long to respond.`);
  }

// Listen for reject events emitted when the
// circuit breaker has an open or half-open state
circuit.on('reject',
  (result) => {
    console.log(`REJECTED: The breaker for ${url} is open. Failing fast.`);
  }

// Listen for open events emitted when the
// circuit breaker moves to an open state
circuit.on('open',
  (result) => {
    console.log(`OPEN: The breaker for ${url} just opened.`);
  }

// Listen for halfOpen events emitted when the
// circuit breaker moves to a half-open state
circuit.on('halfOpen',
  (result) => {
    console.log(`HALF_OPEN: The breaker for ${url} is half open.`);
  }

// Listen for close events emitted when the
// circuit breaker moves to a closed state
circuit.on('close',
  (result) => {
    console.log(`CLOSE: The breaker for ${url} has closed. Service OK.`);
  }

// Listen for fallback events emitted when
// a fallback function is executed
circuit.on('fallback',
  (result) => {
    console.log(`FALLBACK: ${JSON.stringify(data)}`);
  }
Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat