熔断意义
熔断器是当依赖的服务已经出现故障时,为了保证自身服务的正常运行不再访问依赖的服务,防止雪崩效应。
降级意义
当服务器压力剧增时,根据业务策略降级,以此释放服务资源保证业务正常。
关闭状态
服务正常,维护失败率统计,达到失败率阈值时,转到开启状态。
开启状态
服务异常,调用fallback函数,一段时间后,进入半开启状态。
半开启状态
尝试恢复服务,失败率高于阈值,进入开启状态,低于阈值,进入关闭状态。
hystrix-go类库
hystrix-go是熔断、降级、限流集成类库
hystrix-go基本使用
hystrix-go dashboardhystrix-go核心源码
package main import ( "github.com/e421083458/gateway_demo/proxy/middleware" "github.com/e421083458/gateway_demo/proxy/proxy" "github.com/e421083458/gateway_demo/proxy/public" "log" "net/http" "net/url" ) var addr = "127.0.0.1:2002" // 熔断方案 func main() { coreFunc := func(c *middleware.SliceRouterContext) http.Handler { rs1 := "http://127.0.0.1:2003/base" url1, err1 := url.Parse(rs1) if err1 != nil { log.Println(err1) } rs2 := "http://127.0.0.1:2004/base" url2, err2 := url.Parse(rs2) if err2 != nil { log.Println(err2) } urls := []*url.URL{url1, url2} return proxy.NewMultipleHostsReverseProxy(c, urls) } log.Println("Starting httpserver at " + addr) public.ConfCricuitBreaker(true) sliceRouter := middleware.NewSliceRouter() sliceRouter.Group("/").Use(middleware.CircuitMW()) routerHandler := middleware.NewSliceRouterHandler(coreFunc, sliceRouter) log.Fatal(http.ListenAndServe(addr, routerHandler)) }
测试结果
=== RUN Test_main 2021/06/20 18:36:24 hystrix err:service error 2021/06/20 18:36:25 sleep 1 second 2021/06/20 18:36:25 hystrix err:hystrix: circuit open 2021/06/20 18:36:26 sleep 1 second 2021/06/20 18:36:26 hystrix err:hystrix: circuit open 2021/06/20 18:36:27 sleep 1 second 2021/06/20 18:36:27 hystrix err:hystrix: circuit open 2021/06/20 18:36:28 sleep 1 second 2021/06/20 18:36:28 hystrix err:hystrix: circuit open 2021/06/20 18:36:29 sleep 1 second 2021/06/20 18:36:29 hystrix err:hystrix: circuit open 2021/06/20 18:36:30 sleep 1 second 2021/06/20 18:36:30 do services 2021/06/20 18:36:30 do services 2021/06/20 18:36:30 do services
一直都能取到,只有去的间隙过快的时候才会说有取不到的结果
hystrix-go github地址
hystrix-go核心源码实现功能