forked from weibocom/motan-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfailoverHA.go
55 lines (48 loc) · 1.76 KB
/
failoverHA.go
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
package ha
import (
"fmt"
motan "github.com/weibocom/motan-go/core"
"github.com/weibocom/motan-go/log"
)
const (
defaultRetries = 0
)
type FailOverHA struct {
url *motan.URL
}
func (f *FailOverHA) GetName() string {
return FailOver
}
func (f *FailOverHA) GetURL() *motan.URL {
return f.url
}
func (f *FailOverHA) SetURL(url *motan.URL) {
f.url = url
}
func (f *FailOverHA) Call(request motan.Request, loadBalance motan.LoadBalance) motan.Response {
retries := f.url.GetMethodPositiveIntValue(request.GetMethod(), request.GetMethodDesc(), motan.RetriesKey, defaultRetries)
var lastErr *motan.Exception
for i := 0; i <= int(retries); i++ {
ep := loadBalance.Select(request)
if ep == nil {
return getErrorResponseWithCode(request.GetRequestID(), motan.ENoEndpoints,
fmt.Sprintf("No refers for request, RequestID: %d, Request info: %+v",
request.GetRequestID(), request.GetAttachments().RawMap()))
}
response := ep.Call(request)
if response.GetException() == nil || response.GetException().ErrType == motan.BizException {
return response
}
lastErr = response.GetException()
vlog.Warningf("FailOverHA call fail! url:%s, err:%+v", ep.GetURL().GetIdentity(), lastErr)
}
errorResponse := getErrorResponse(request.GetRequestID(), fmt.Sprintf("FailOverHA call fail %d times. Exception: %s", retries+1, lastErr.ErrMsg))
errorResponse.Exception.ErrCode = lastErr.ErrCode
return errorResponse
}
func getErrorResponse(requestID uint64, errMsg string) *motan.MotanResponse {
return getErrorResponseWithCode(requestID, 400, errMsg)
}
func getErrorResponseWithCode(requestID uint64, errCode int, errMsg string) *motan.MotanResponse {
return motan.BuildExceptionResponse(requestID, &motan.Exception{ErrCode: errCode, ErrMsg: errMsg, ErrType: motan.ServiceException})
}