forked from easierway/service_decorators
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
68 lines (57 loc) · 1.56 KB
/
example_test.go
File metadata and controls
68 lines (57 loc) · 1.56 KB
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
64
65
66
67
68
package service_decorators
import (
"errors"
"fmt"
"testing"
"time"
"github.com/easierway/g_met"
)
func originalFunction(a int, b int) (int, error) {
return a + b, nil
}
func Example() {
// Encapsulate the original function as service_decorators.serviceFunc method signature
type encapsulatedReq struct {
a int
b int
}
encapsulatedFn := func(req Request) (Response, error) {
innerReq, ok := req.(encapsulatedReq)
if !ok {
return nil, errors.New("invalid parameters")
}
return originalFunction(innerReq.a, innerReq.b)
}
// Add the logics with decorators
// 1. Create the decorators
var (
retryDec *RetryDecorator
circuitBreakDec *CircuitBreakDecorator
metricDec *MetricDecorator
err error
)
if retryDec, err = CreateRetryDecorator(3 /*max retry times*/, time.Second*1,
time.Second*1, retriableChecker); err != nil {
panic(err)
}
if circuitBreakDec, err = CreateCircuitBreakDecorator().
WithTimeout(time.Millisecond * 100).
WithMaxCurrentRequests(1000).
Build(); err != nil {
panic(err)
}
gmet := g_met.CreateGMetInstanceByDefault("g_met_config/gmet_config.xml")
if metricDec, err = CreateMetricDecorator(gmet).
NeedsRecordingTimeSpent().Build(); err != nil {
panic(err)
}
// 2. decorate the encapsulted function with decorators
// be careful of the order of the decorators
decFn := circuitBreakDec.Decorate(metricDec.Decorate(retryDec.Decorate(encapsulatedFn)))
ret, err := decFn(encapsulatedReq{1, 2})
fmt.Println(ret, err)
//Output: 3 <nil>
}
func TestExample(t *testing.T) {
Example()
}