A circuit breaker code example

The following code is an example of a circuit breaker using Ballerina. It will be listening on the port:9090 TCP, as well as on port:9091 TCP. The code is much more readable for programmers than the code for other languages:

//Circuit breaking example from https://ballerina.io/
import ballerina/http;
import ballerina/io;

string previousRes;

endpoint http:Listener listener {
port:9090
};

// Endpoint with circuit breaker can short circuit responses under
// some conditions. Circuit flips to OPEN state when errors or
// responses take longer than timeout. OPEN circuits bypass
// endpoint and return error.
endpoint http:Client legacyServiceResilientEP {
url: "http://localhost:9091",
circuitBreaker: {
// Failure calculation window
rollingWindow: {
// Duration of the window
timeWindowMillis: 10000,

// Each time window is divided into buckets
bucketSizeMillis: 2000,

// Min # of requests in a `RollingWindow` to trip circuit
requestVolumeThreshold: 0
},

// Percentage of failures allowed
failureThreshold: 0.0,

// Reset circuit to CLOSED state after timeout
resetTimeMillis: 1000,

// Error codes that open the circuit
statusCodes: [400, 404, 500]
},

// Invocation timeout - independent of circuit
timeoutMillis: 2000
};

The preceding code is for legacyServiceResilientEP with various circuit breaker definitions. The following code is a further extension of this, in which we are defining various paths and methods with circuit breaker condition definitions, according to which the code will respond:


@http:ServiceConfig {
basePath:"/resilient/time"
}
service<http:Service> timeInfo bind listener {

@http:ResourceConfig {
methods:["GET"],
path:"/"
}
getTime (endpoint caller, http:Request req) {

var response = legacyServiceResilientEP ->
get("/legacy/localtime");

match response {

// Circuit breaker not tripped
http:Response res => {
http:Response okResponse = new;
if (res.statusCode == 200) {

string payloadContent = check res.getTextPayload();
previousRes = untaint payloadContent;
okResponse.setTextPayload(untaint payloadContent);
io:println("Remote service OK, data received");

} else {

// Remote endpoint returns an error
io:println("Error received from "+"remote service.");
okResponse.setTextPayload("Previous Response : "
+ previousRes);

}
okResponse.statusCode = http:OK_200;
_ = caller -> respond(okResponse);
}

// Circuit breaker tripped and generates error
error err => {
http:Response errResponse = new;
io:println("Circuit open, using cached data");
errResponse.setTextPayload( "Previous Response : "
+ previousRes);

// Inform client service is unavailable
errResponse.statusCode = http:OK_200;
_ = caller -> respond(errResponse);
}
}
}
}

The following screenshot shows the circuit breaker code flow diagram: 

           
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.16.254