This repository has been archived by the owner on Oct 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
7_demo_circuit_breaker.bal
63 lines (57 loc) · 1.85 KB
/
7_demo_circuit_breaker.bal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// To compensate for slowness use circuit breaker
// To run it:
// ballerina run 7_demo_circuit_breaker.bal --b7a.config.file=twitter.toml
// To invoke:
// curl -X POST localhost:9090
// Invoke many times to show how circuit breaker works
import ballerina/config;
import ballerina/http;
import ballerina/stringutils;
import wso2/twitter;
http:Client homer = new ("http://quotes.rest", config = {
circuitBreaker: {
failureThreshold: 0.0,
resetTimeInMillis: 3000,
statusCodes: [500, 501, 502]
},
timeoutInMillis: 900
});
twitter:Client tw = new ({
clientId: config:getAsString("clientId"),
clientSecret: config:getAsString("clientSecret"),
accessToken: config:getAsString("accessToken"),
accessTokenSecret: config:getAsString("accessTokenSecret"),
clientConfig: {}
});
@http:ServiceConfig {
basePath: "/"
}
service hello on new http:Listener(9090) {
@http:ResourceConfig {
path: "/",
methods: ["POST"]
}
resource function hi(http:Caller caller, http:Request request) returns error? {
http:Response res = new;
var hResp = homer->get("/qod.json");
if (hResp is http:Response) {
json payload = check hResp.getJsonPayload();
json[] quotes = <json[]>(payload.contents.quotes);
string status = quotes[0].quote.toString();
if (!stringutils:contains(status, "#ballerina")) {
status = status + " #ballerina";
}
var st = check tw->tweet(status);
json myJson = {
text: payload,
id: st.id,
agent: "ballerina"
};
res.setPayload(<@untainted>myJson);
} else {
res.setPayload("Circuit is open. Invoking default behavior.\n");
}
_ = check caller->respond(res);
return;
}
}