基于函数的 熔断器,限流器
上一篇博文写了我的naocs sdk,但啥都有了,那微服务关键的熔断和限流的功能也必须安排上。虽然说是微服务的熔断器和限流器,但是你只要导入并创建好对应的熔断器和限流器,你可以用在函数上面,替你处理函数超时响应以及函数异常。也可以对你的函数做限流和熔断。
我的git地址:https://github.com/KcangYan/nacos-python-sdk
熔断器
在自己的项目中使用
pip install KcangFuse #安装
import KcangFuse.funcFuse as funcFuse
使用说明:
```
def myFallBackFunc(*args,**kwargs):#自定义熔断返回函数
return "function fallback " + " function info: " + str(args)+ " " + str(kwargs)
def myTimeoutFallbackFunc(ex, *args,**kwargs): #自定义错误返回函数
print(ex)
return "function time out " + " function info: " + str(args)+ " " + str(kwargs)
def myExceptFallbackFunc(ex, *args,**kwargs): #自定义超时返回函数
return "function except " + str(ex) + " function info: " + str(args)+ " " + str(kwargs)
```
当开启熔断时,即返回自定义熔断返回函数,不开启根据情况返回其他两个
```
SimpleFuncFuse1 = funcFuse.funcFuse()#不设置则使用内置默认错误返回函数
注意:注解需声明在函数上方,不可以在@app这个注解上方,否则不生效!
@app.route(Router + "/test1", methods=['GET'])
@SimpleFuncFuse1.fuse(timeout=2)
def fuseTest1():#超时返回自定义超时错误返回函数
time.sleep(3)
return "ok"
```
```
SimpleFuncFuse2 = funcFuse.funcFuse(timeoutFallbackFunc=myTimeoutFallbackFunc,
exceptFallbackFunc=myExceptFallbackFunc)
可以尝试让路由映射的函数发生异常,熔断器会将详细的函数信息返回给自定义异常返回函数,交由你自己处理
@app.route(Router + "/test2/<int:x>/<int:y>", methods=['GET'])
@SimpleFuncFuse2.fuse()
def fuseTest2(x,y):
z = x/y #路由中输入0尝试错误返回自定义函数
return str(z)
```
fuseStatus=True时则表示开启熔断器模式(默认是关闭的)
exceptPercent=0.5, 0-1之间 异常比例,即在熔断统计时间窗口期内发生异常的比例
timeWindows=5, 单位:秒 熔断时间窗口期,即触发熔断后熔断多久,熔断时间窗口期过去后,会自动再放开请求进去,
如果异常比例还是很高的话,则继续熔断。
timeCount=2, 单位:秒 熔断统计异常时间窗口期,即统计异常的时间段长度。建议1-2秒
```
SimpleFuncFuse3 = funcFuse.funcFuse(fallbackFunc=myFallBackFunc)
@app.route(Router + "/test3", methods=['GET'])
@SimpleFuncFuse3.fuse(timeout=2,fuseStatus=True,exceptPercent=0.5,timeWindows=5,timeCount=2)
def fuseTest3(): #超时熔断
time.sleep(3)
return "ok"
@app.route(Router + "/test4/<int:x>/<int:y>", methods=['GET'])
@SimpleFuncFuse3.fuse(fuseStatus=True, exceptPercent=0.5,timeWindows=5,timeCount=2)
def fuseTest4(x, y):
z = x / y # 路由中输入0尝试错误熔断
return str(z)
```
限流器
在自己的项目中使用
```
pip install KcangFuse
import KcangFuse.funcFuse as funcFuse
```
建立限流器类,并赋予自定义的限流返回函数
```
flowControl = funcFuse.funcFlowControl(fallBackFunc=myFallBackFunc)
```
timeWindows=2, 单位秒 限流时间窗口期
maxCount=5 允许请求数 即 在限流时间窗口期内 最多允许5个请求在处理,可以理解为最多五个线程
可以和熔断器注解一起使用!
```
@app.route(Router + "/test5", methods=['GET'])
@SimpleFuncFuse3.fuse(timeout=2)
@flowControl.flowControl(timeWindows=2,maxCount=5)
def fuseTest5(): #尝试这个demo 即可
time.sleep(3)
return "ok"
```
可以尝试一下下面这个demo调用上面这个接口,看看效果
```python
def t5(count):
re = requests.get("http://127.0.0.1:8080/fuse/test5")
print(re.text + " 当前线程:"+str(count)+"\n")
if __name__ == '__main__':
import requests,threading
for i in range(0,200):
threading.Thread(target=t5,args=(i,)).start()
time.sleep(5)
```
结尾
后续如果有什么问题,我会第一时间更新在github上,只要pip install更新版本即可