3.2. greeting-service の例
greeting-service は、サーキットブレーカーアドオンをインポートします。greeting-service は、これらの呼び出しをサーキットブレーカーオブジェクトでラップすることにより、リモート name-service への呼び出しを保護します。
greeting-service は以下のエンドポイントを公開します。
-
/api/greetingエンドポイントは、グリーティングを要求する Web クライアントから呼び出しを受け取ります。/api/greetingエンドポイントは、クライアント要求の処理の一環として、リモートname-serviceの/api/nameエンドポイントに呼び出しを送信します。/api/nameエンドポイントへの呼び出しは、サーキットブレーカーオブジェクトにラップされます。リモートname-serviceが現在利用可能な場合、/api/greetingエンドポイントはグリーティングをクライアントに送信します。ただし、リモートname-serviceが現在利用不可の場合、/api/greetingエンドポイントはエラー応答をクライアントに送信します。 -
/api/cb-stateエンドポイントは、サーキットブレーカーの現在の状態を返します。これがopenに設定されている場合、サーキットブレーカーは現在、失敗したサービスに要求が到達できないようにします。これがclosedに設定されている場合、サーキットブレーカーは現在、要求がサービスに到達できるようにしています。
以下のコード例は、greeting-service を開発する方法を示しています。
'use strict';
const path = require('path');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
// Import the circuit breaker add-on
const Opossum = require('@redhat/opossum');
const probe = require('kube-probe');
const nameService = require('./lib/name-service-client');
const app = express();
const server = http.createServer(app);
// Add basic health check endpoints
probe(app);
const nameServiceHost = process.env.NAME_SERVICE_HOST || 'http://nodejs-circuit-breaker-redhat-name:8080';
// Set some circuit breaker options
const circuitOptions = {
timeout: 3000, // If name service takes longer than 0.3 seconds,
// trigger a failure
errorThresholdPercentage: 50, // When 50% of requests fail,
// trip the circuit
resetTimeout: 10000 // After 10 seconds, try again.
};
// Create a new circuit breaker instance and pass the remote nameService
// as its first parameter
const circuit = new Opossum(nameService, circuitOptions);
// Create the app with an initial websocket endpoint
require('./lib/web-socket')(server, circuit);
// Serve index.html from the file system
app.use(express.static(path.join(__dirname, 'public')));
// Expose the license.html at http[s]://[host]:[port]/licences/licenses.html
app.use('/licenses', express.static(path.join(__dirname, 'licenses')));
// Send and receive json
app.use(bodyParser.json());
// Greeting API
app.get('/api/greeting', (request, response) => {
// Use the circuit breaker’s fire method to execute the call
// to the name service
circuit.fire(`${nameServiceHost}/api/name`).then(name => {
response.send({ content: `Hello, ${name}`, time: new Date() });
}).catch(console.error);
});
// Circuit breaker state API
app.get('/api/cb-state', (request, response) => {
response.send({ state: circuit.opened ? 'open' : 'closed' });
});
app.get('/api/name-service-host', (request, response) => {
response.send({ host: nameServiceHost });
});
module.exports = server;