主要包含断路器模式,负载均衡模式,故障转移,重试

Circuit Breaker

  • 参考代码
import ballerina/http;
import ballerina/log;
import ballerina/runtime;
endpoint http:Client backendClientEP {
url: "http://localhost:8080",
circuitBreaker: {
rollingWindow: {
timeWindowMillis: 10000,
bucketSizeMillis: 2000
},
failureThreshold: 0.2,
resetTimeMillis: 10000,
statusCodes: [400, 404, 500]
}, timeoutMillis: 2000
};
@http:ServiceConfig {
basePath: "/cb"
}
service<http:Service> circuitbreaker bind { port: 9090 } {
@http:ResourceConfig {
methods: ["GET"],
path: "/"
}
invokeEndpoint(endpoint caller, http:Request request) {
var backendRes = backendClientEP->forward("/hello", request);
match backendRes { http:Response res => {
caller->respond(res) but {
error e => log:printError("Error sending response", err = e)
};
}
error responseError => {
http:Response response = new;
response.statusCode = 500;
response.setPayload(responseError.message);
caller->respond(response) but {
error e => log:printError("Error sending response", err = e)
};
}
}
}
}
public int counter = 1;
@http:ServiceConfig { basePath: "/hello" }
service<http:Service> helloWorld bind { port: 8080 } {
@http:ResourceConfig {
methods: ["GET"],
path: "/"
}
sayHello(endpoint caller, http:Request req) {
if (counter % 5 == 0) {
runtime:sleep(5000); counter = counter + 1;
http:Response res = new;
res.setPayload("Hello World!!!");
caller->respond(res) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
} else if (counter % 5 == 3) {
counter = counter + 1;
http:Response res = new;
res.statusCode = 500;
res.setPayload(
"Internal error occurred while processing the request.");
caller->respond(res) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
} else {
counter = counter + 1;
http:Response res = new;
res.setPayload("Hello World!!!");
caller->respond(res) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
}
}
}

Load Balancing(http)

  • 参考代码
import ballerina/http;
import ballerina/log;
endpoint http:Listener backendEP {
port: 8080
};
endpoint http:LoadBalanceClient lbBackendEP {
targets: [
{ url: "http://localhost:8080/mock1" },
{ url: "http://localhost:8080/mock2" },
{ url: "http://localhost:8080/mock3" }
],
algorithm: http:ROUND_ROBIN,
timeoutMillis: 5000
};
@http:ServiceConfig {
basePath: "/lb"
}
service<http:Service> loadBalancerDemoService bind { port: 9090 } {
@http:ResourceConfig {
path: "/"
}
invokeEndpoint(endpoint caller, http:Request req) {
http:Request outRequest = new;
json requestPayload = { "name": "Ballerina" };
outRequest.setPayload(requestPayload);
var response = lbBackendEP->post("/", request = outRequest);
match response {
http:Response resp => {
caller->respond(resp) but {
error e => log:printError("Error sending response", err = e)
};
}
error responseError => {
http:Response outResponse = new;
outResponse.statusCode = 500;
outResponse.setPayload(responseError.message);
caller->respond(outResponse) but {
error e => log:printError("Error sending response", err = e)
};
}
}
}
}
@http:ServiceConfig { basePath: "/mock1" }
service mock1 bind backendEP {
@http:ResourceConfig {
path: "/"
}
mock1Resource(endpoint caller, http:Request req) {
http:Response outResponse = new;
outResponse.setPayload("Mock1 Resource is invoked.");
caller->respond(outResponse) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
}
}@http:ServiceConfig { basePath: "/mock2" }
service mock2 bind backendEP {
@http:ResourceConfig {
path: "/"
}
mock2Resource(endpoint caller, http:Request req) {
http:Response outResponse = new;
outResponse.setPayload("Mock2 Resource is Invoked.");
caller->respond(outResponse) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
}
}@http:ServiceConfig { basePath: "/mock3" }
service mock3 bind backendEP {
@http:ResourceConfig {
path: "/"
}
mock3Resource(endpoint caller, http:Request req) {
http:Response outResponse = new;
outResponse.setPayload("Mock3 Resource is Invoked.");
caller->respond(outResponse) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
}
}

Failover

  • 参考代码
import ballerina/http;
import ballerina/log;
import ballerina/runtime;
endpoint http:Listener backendEP {
port: 8080
};
endpoint http:FailoverClient foBackendEP {
timeoutMillis: 5000,
failoverCodes: [501, 502, 503],
intervalMillis: 5000,
targets: [
{ url: "http://localhost:3000/mock1" },
{ url: "http://localhost:8080/echo" },
{ url: "http://localhost:8080/mock" }
]};
@http:ServiceConfig {
basePath: "/fo"
}
service<http:Service> failoverDemoService bind { port: 9090 } {
@http:ResourceConfig {
methods: ["GET", "POST"],
path: "/"
}
invokeEndpoint(endpoint caller, http:Request request) {
var backendRes = foBackendEP->get("/", request = request);
match backendRes {
http:Response response => {
caller->respond(response) but {
error e => log:printError("Error sending response", err = e)
};
}
error responseError => {
http:Response response = new;
response.statusCode = 500;
response.setPayload(responseError.message);
caller->respond(response) but {
error e => log:printError("Error sending response", err = e)
};
}
}
}
}
@http:ServiceConfig {
basePath: "/echo"
}
service echo bind backendEP {
@http:ResourceConfig {
methods: ["POST", "PUT", "GET"],
path: "/"
}
echoResource(endpoint caller, http:Request req) {
http:Response outResponse = new;
runtime:sleep(30000); outResponse.setPayload("echo Resource is invoked");
caller->respond(outResponse) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
}
}
@http:ServiceConfig {
basePath: "/mock"
}
service mock bind backendEP {
@http:ResourceConfig {
methods: ["POST", "PUT", "GET"],
path: "/"
}
mockResource(endpoint caller, http:Request req) {
http:Response outResponse = new;
outResponse.setPayload("Mock Resource is Invoked.");
caller->respond(outResponse) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
}
}

Retry

  • 参考代码
import ballerina/http;
import ballerina/log;
import ballerina/runtime;
endpoint http:Client backendClientEP {
url: "http://localhost:8080",
retryConfig: {
interval: 3000,
count: 3,
backOffFactor: 0.5
}, timeoutMillis: 2000
};@http:ServiceConfig {
basePath: "/retry"
}
service<http:Service> retryDemoService bind { port: 9090 } {
@http:ResourceConfig {
methods: ["GET"],
path: "/"
}
invokeEndpoint(endpoint caller, http:Request request) {
var backendResponse = backendClientEP->get("/hello", request = request);
match backendResponse { http:Response response => {
caller->respond(response) but {
error e => log:printError("Error sending response", err = e)
}; }
error responseError => {
http:Response errorResponse = new;
errorResponse.statusCode = 500;
errorResponse.setPayload(responseError.message); caller->respond(errorResponse) but {
error e => log:printError("Error sending response", err = e)
};
}
}
}
}public int counter = 0;@http:ServiceConfig { basePath: "/hello" }
service<http:Service> mockHelloService bind { port: 8080 } {
@http:ResourceConfig {
methods: ["GET"],
path: "/"
}
sayHello(endpoint caller, http:Request req) {
counter = counter + 1;
if (counter % 4 != 0) {
log:printInfo(
"Request received from the client to delayed service.");
runtime:sleep(5000); http:Response res = new;
res.setPayload("Hello World!!!");
caller->respond(res) but {
error e => log:printError(
"Error sending response from mock service", err = e)
};
} else {
log:printInfo(
"Request received from the client to healthy service.");
http:Response res = new;
res.setPayload("Hello World!!!");
caller->respond(res) but {
error e => log:printError(
"Error sending response from mock service", err = e) };
}
}
}

参考资料

https://ballerina.io/learn/by-example/http-failover.html
https://ballerina.io/learn/by-example/http-circuit-breaker.html
https://ballerina.io/learn/by-example/http-load-balancer.html
https://ballerina.io/learn/by-example/http-retry.html

 
 
 
 

ballerina 学习二十二 弹性服务的更多相关文章

  1. ballerina 学习 三十二 编写安全的程序

      ballerina编译器已经集成了部分安全检测,在编译时可以帮助我们生成错误提示,同时ballerina 标准库 已经对于常见漏洞高发的地方做了很好的处理,当我们编写了有安全隐患的代码,编译器就已 ...

  2. WCF技术剖析之二十四: ServiceDebugBehavior服务行为是如何实现异常的传播的?

    原文:WCF技术剖析之二十四: ServiceDebugBehavior服务行为是如何实现异常的传播的? 服务端只有抛出FaultException异常才能被正常地序列化成Fault消息,并实现向客户 ...

  3. python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字

    python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字在字符串里面插入指定分割符的方法,先把字符串变成list然后用join方法变成字符串str=' ...

  4. python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL

    python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(a ...

  5. Go语言学习笔记十二: 范围(Range)

    Go语言学习笔记十二: 范围(Range) rang这个关键字主要用来遍历数组,切片,通道或Map.在数组和切片中返回索引值,在Map中返回key. 这个特别像python的方式.不过写法上比较怪异使 ...

  6. Tensorflow深度学习之十二:基础图像处理之二

    Tensorflow深度学习之十二:基础图像处理之二 from:https://blog.csdn.net/davincil/article/details/76598474   首先放出原始图像: ...

  7. 学习笔记:CentOS7学习之二十二: 结构化命令case和for、while循环

    目录 学习笔记:CentOS7学习之二十二: 结构化命令case和for.while循环 22.1 流程控制语句:case 22.2 循环语句 22.1.2 for-do-done 22.3 whil ...

  8. (C/C++学习笔记) 二十二. 标准模板库

    二十二. 标准模板库 ● STL基本介绍 标准模板库(STL, standard template library): C++提供的大量的函数模板(通用算法)和类模板. ※ 为什么我们一般不需要自己写 ...

  9. VMware vSphere 服务器虚拟化之二十二桌面虚拟化之创建View Composer链接克隆的虚拟桌面池

    VMware vSphere 服务器虚拟化之二十二桌面虚拟化之创建View Composer链接克隆的虚拟桌面池 在上一节我们创建了完整克隆的自动专有桌面池,在创建过程比较缓慢,这次我们将学习创建Vi ...

  10. Bootstrap <基础二十二>超大屏幕(Jumbotron)

    Bootstrap 支持的另一个特性,超大屏幕(Jumbotron).顾名思义该组件可以增加标题的大小,并为登陆页面内容添加更多的外边距(margin).使用超大屏幕(Jumbotron)的步骤如下: ...

随机推荐

  1. SQLServer cast()函数

    语法: CAST (expression AS data_type) 参数说明: expression:任何有效的SQLServer表达式. AS:用于分隔两个参数,在AS之前的是要处理的数据,在AS ...

  2. Gulp命令自动生成精灵图

    文件目录说明 gulpfile.js代码 var gulp = require('gulp'); var spritesmith = require('gulp.spritesmith'); var ...

  3. 在JAVA可移植性的来源的三方面

    软件可移植性的概念是与软件从某一环境转移到另一环境下的难易程度.为获得较高的可移植性,在设计过程中常采用通用的程序设计语言和运行支撑环境.尽量不用与系统的底层相关性强的语言.下面介绍JAVA的可移植性 ...

  4. 欧几里德和扩展欧几里德详解 以及例题CodeForces 7C

    欧几里德定理: 对于整数a,b来说,gcd(a, b)==gcd(b, a%b)==d(a与b的最大公约数),又称为辗转相除法 证明: 因为a是d的倍数,b是d的倍数:所以a%d==0:b%d==0: ...

  5. Solidity 官方文档中文版 1_简介

    简介 Solidity是一种语法类似JavaScript的高级语言.它被设计成以编译的方式生成以太坊虚拟机代码.在后续内容中你将会发现,使用它很容易创建用于投票.众筹.封闭拍卖.多重签名钱包等等的合约 ...

  6. BZOJ 2876 【NOI2012】 骑行川藏

    题目链接:骑行川藏 听说这道题需要一些高数知识 于是膜了一发dalao的题解……然后就没了…… 不要吐槽我的精度TAT……eps设太小了就TLE,大了就Wa……我二分的边界是对着数据卡的…… 下面贴代 ...

  7. shell 判断是否是目录

    创建一个文件和一个文件夹 touch sss mkdir d test.sh #!/bin/bash echo "enter the name:" read filename if ...

  8. hdu4565矩阵快速幂

    这题太坑了...刚开始以为可以用|a+sqrt(b)  1|水过...结果tle,还一直想明明我logn的做法怎么可能tle.. |    0           1| 实在无奈看的题解 (a+sqr ...

  9. UVA-11248 Frequency Hopping (最大流+最小割)

    题目大意:给一张网络,问是否存在一条恰为C的流.若不存在,那是否存在一条弧,使得改动这条弧的容量后能恰有为C的流? 题目分析:先找出最大流,如果最大流不比C小,那么一定存在一条恰为C的流.否则,找出最 ...

  10. Python自动化运维之路-01

    python的主要应用 python的擅长领域 学python有没有前途?python的语言排名 语言选择 运维会了开发后可以干什么? python的最大优势就是什么都能做. 课程概述 毕业目标 周五 ...