cubefs
79 строк · 2.6 Кб
1/*
2Package hystrix is a latency and fault tolerance library designed to isolate
3points of access to remote systems, services and 3rd party libraries, stop
4cascading failure and enable resilience in complex distributed systems where
5failure is inevitable.
6
7Based on the java project of the same name, by Netflix. https://github.com/Netflix/Hystrix
8
9Execute code as a Hystrix command
10
11Define your application logic which relies on external systems, passing your function to Go. When that system is healthy this will be the only thing which executes.
12
13hystrix.Go("my_command", func() error {
14// talk to other services
15return nil
16}, nil)
17
18Defining fallback behavior
19
20If you want code to execute during a service outage, pass in a second function to Go. Ideally, the logic here will allow your application to gracefully handle external services being unavailable.
21
22This triggers when your code returns an error, or whenever it is unable to complete based on a variety of health checks https://github.com/Netflix/Hystrix/wiki/How-it-Works.
23
24hystrix.Go("my_command", func() error {
25// talk to other services
26return nil
27}, func(err error) error {
28// do this when services are down
29return nil
30})
31
32Waiting for output
33
34Calling Go is like launching a goroutine, except you receive a channel of errors you can choose to monitor.
35
36output := make(chan bool, 1)
37errors := hystrix.Go("my_command", func() error {
38// talk to other services
39output <- true
40return nil
41}, nil)
42
43select {
44case out := <-output:
45// success
46case err := <-errors:
47// failure
48}
49
50Synchronous API
51
52Since calling a command and immediately waiting for it to finish is a common pattern, a synchronous API is available with the Do function which returns a single error.
53
54err := hystrix.Do("my_command", func() error {
55// talk to other services
56return nil
57}, nil)
58
59Configure settings
60
61During application boot, you can call ConfigureCommand to tweak the settings for each command.
62
63hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
64Timeout: 1000,
65MaxConcurrentRequests: 100,
66ErrorPercentThreshold: 25,
67})
68
69You can also use Configure which accepts a map[string]CommandConfig.
70
71Enable dashboard metrics
72
73In your main.go, register the event stream HTTP handler on a port and launch it in a goroutine. Once you configure turbine for your Hystrix Dashboard https://github.com/Netflix/Hystrix/tree/master/hystrix-dashboard to start streaming events, your commands will automatically begin appearing.
74
75hystrixStreamHandler := hystrix.NewStreamHandler()
76hystrixStreamHandler.Start()
77go http.ListenAndServe(net.JoinHostPort("", "81"), hystrixStreamHandler)
78*/
79package hystrix80