11package com .tencent .bk .devops .atom .api ;
22
3-
43import com .google .common .collect .Maps ;
54import com .tencent .bk .devops .atom .exception .RemoteServiceException ;
65import com .tencent .bk .devops .atom .utils .json .JsonUtil ;
6+ import java .io .IOException ;
7+ import java .io .UnsupportedEncodingException ;
8+ import java .net .HttpRetryException ;
9+ import java .net .SocketTimeoutException ;
10+ import java .net .URLEncoder ;
11+ import java .net .UnknownHostException ;
12+ import java .rmi .ConnectException ;
13+ import java .util .Arrays ;
14+ import java .util .Map ;
15+ import java .util .concurrent .TimeUnit ;
716import okhttp3 .Headers ;
817import okhttp3 .MediaType ;
918import okhttp3 .OkHttpClient ;
1322import org .slf4j .Logger ;
1423import org .slf4j .LoggerFactory ;
1524
16- import java .io .IOException ;
17- import java .io .UnsupportedEncodingException ;
18- import java .net .URLEncoder ;
19- import java .util .Map ;
20- import java .util .concurrent .TimeUnit ;
21-
2225public class BaseApi {
2326
24- protected static final MediaType JSON_CONTENT_TYPE = MediaType .parse ("application/json; charset=utf-8" );
27+ protected static final MediaType JSON_CONTENT_TYPE =
28+ MediaType .parse ("application/json; charset=utf-8" );
2529 private static final Logger logger = LoggerFactory .getLogger (BaseApi .class );
30+ private static final long sleepTimeMills = 500L ;
31+ private static final int DEFAULT_RETRY_TIME = 5 ;
32+
33+ protected Response requestForResponse (Request request , int retryCount )
34+ throws IOException , InterruptedException {
35+ OkHttpClient httpClient = okHttpClient .newBuilder ().build ();
36+ boolean retryFlag ;
37+ try {
38+ Response response = httpClient .newCall (request ).execute ();
39+ if (Arrays .asList (502 , 503 , 504 ).contains (response .code ())) {
40+ retryFlag = true ;
41+ } else {
42+ return response ;
43+ }
44+ } catch (UnknownHostException e ) {
45+ logger .warn (
46+ "UnknownHostException|request({}),error is :{}, try to retry {}" ,
47+ request ,
48+ e .getMessage (),
49+ retryCount );
50+ retryFlag = retryCount > 0 ;
51+ } catch (ConnectException e ) {
52+ logger .warn (
53+ "ConnectException|request({}),error is :{}, try to retry {}" ,
54+ request ,
55+ e .getMessage (),
56+ retryCount );
57+ retryFlag = retryCount > 0 ;
58+ } catch (SocketTimeoutException re ) {
59+ if ("connect timed out" .equals (re .getMessage ())
60+ || ("GET" .equals (request .method ()) && "timeout" .equals (re .getMessage ()))) {
61+ logger .warn (
62+ "SocketTimeoutException|request({}),error is :{}, try to retry {}" ,
63+ request ,
64+ re .getMessage (),
65+ retryCount );
66+ retryFlag = retryCount > 0 ;
67+ } else {
68+ logger .error ("Fail to request({})" , request , re );
69+ throw re ;
70+ }
71+ } catch (Exception error ) {
72+ logger .error ("Fail to request({})" , request , error );
73+ throw new RemoteServiceException (
74+ String .format ("Fail to request(%s),error is:%s" , request , error .getMessage ()), 500 , "" );
75+ }
76+ if (retryFlag && retryCount > 0 ) {
77+ logger .warn ("Fail to request({}), retry after {} ms" , request , sleepTimeMills );
78+ Thread .sleep (sleepTimeMills );
79+ return requestForResponse (request , retryCount - 1 );
80+ } else {
81+ logger .error ("Fail to request({}), try to retry {}" , request , retryCount );
82+ throw new HttpRetryException (
83+ String .format ("Fail to request(%s), try to retry %s" , request , retryCount ), 999 );
84+ }
85+ }
86+
87+ protected String retryRequest (Request request , String errorMessage , int retryCount )
88+ throws IOException {
89+ try (Response response = requestForResponse (request , retryCount )) {
90+ String responseContent = response .body () != null ? response .body ().string () : null ;
91+ if (!response .isSuccessful ()) {
92+ logger .error (
93+ "Fail to request("
94+ + request
95+ + ") with code "
96+ + response .code ()
97+ + " , message "
98+ + response .message ()
99+ + " and response"
100+ + responseContent );
101+ logger .info ("excep>>>>>>>>>>>>" + response );
102+ throw new RemoteServiceException (errorMessage , response .code (), responseContent );
103+ }
104+ return responseContent ;
105+ } catch (InterruptedException e ) {
106+ throw new RemoteServiceException (errorMessage , 500 , e .getMessage ());
107+ }
108+ }
109+
110+ protected String retryRequest (Request request , String errorMessage ) throws IOException {
111+ return retryRequest (request , errorMessage , DEFAULT_RETRY_TIME );
112+ }
26113
27- /**
28- * request请求,返回json格式响应报文
29- *
30- * @param request request对象
31- * @param errorMessage 请求错误信息
32- * @return json格式响应报文
33- */
34114 protected String request (Request request , String errorMessage ) throws IOException {
35115 OkHttpClient httpClient = okHttpClient .newBuilder ().build ();
36116 try (Response response = httpClient .newCall (request ).execute ()) {
37117 String responseContent = response .body () != null ? response .body ().string () : null ;
38118 if (!response .isSuccessful ()) {
39- logger .error ("Fail to request(" + request + ") with code " + response .code ()
40- + " , message " + response .message () + " and response" + responseContent );
119+ logger .error (
120+ "Fail to request("
121+ + request
122+ + ") with code "
123+ + response .code ()
124+ + " , message "
125+ + response .message ()
126+ + " and response"
127+ + responseContent );
41128 logger .info ("excep>>>>>>>>>>>>" + response );
42129 throw new RemoteServiceException (errorMessage , response .code (), responseContent );
43130 }
44131 return responseContent ;
45132 }
46133 }
47134
48- private OkHttpClient okHttpClient = new okhttp3 .OkHttpClient .Builder ()
135+ protected OkHttpClient okHttpClient =
136+ new okhttp3 .OkHttpClient .Builder ()
49137 .connectTimeout (5L , TimeUnit .SECONDS )
50138 .readTimeout (300 * 5L , TimeUnit .SECONDS ) // Set to 15 minutes
51139 .writeTimeout (60L , TimeUnit .SECONDS )
52140 .build ();
53141
54- /**
55- * get请求,返回request对象
56- *
57- * @param path 请求路径
58- * @param headers 请求头
59- * @return request对象
60- */
61142 public Request buildGet (String path , Map <String , String > headers ) {
62143 String url = buildUrl (path );
63144 return new Request .Builder ().url (url ).headers (Headers .of (getAllHeaders (headers ))).get ().build ();
64145 }
65146
66- /**
67- * get请求,返回request对象
68- *
69- * @param path 请求路径
70- * @return request对象
71- */
72147 public Request buildGet (String path ) {
73148 return buildGet (path , Maps .newHashMap ());
74149 }
75150
76- /**
77- * post请求,返回request对象
78- *
79- * @param path 请求路径
80- * @return request对象
81- */
82151 public Request buildPost (String path ) {
83152 return buildPost (path , Maps .newHashMap ());
84153 }
85154
86- /**
87- * post请求,返回request对象
88- *
89- * @param path 请求路径
90- * @param headers 请求头
91- * @return request对象
92- */
93155 public Request buildPost (String path , Map <String , String > headers ) {
94- RequestBody requestBody = RequestBody .create (MediaType .parse ("application/json; charset=utf-8" ), "" );
156+ RequestBody requestBody =
157+ RequestBody .create (MediaType .parse ("application/json; charset=utf-8" ), "" );
95158 return buildPost (path , requestBody , headers );
96159 }
97160
98- /**
99- * post请求,返回request对象
100- *
101- * @param path 请求路径
102- * @param requestBody 请求报文体
103- * @param headers 请求头
104- * @return request对象
105- */
106161 public Request buildPost (String path , RequestBody requestBody , Map <String , String > headers ) {
107162 String url = buildUrl (path );
108- return new Request .Builder ().url (url ).headers (Headers .of (getAllHeaders (headers ))).post (requestBody ).build ();
163+ return new Request .Builder ()
164+ .url (url )
165+ .headers (Headers .of (getAllHeaders (headers )))
166+ .post (requestBody )
167+ .build ();
109168 }
110169
111- /**
112- * put请求,返回request对象
113- *
114- * @param path 请求路径
115- * @return request对象
116- */
117170 public Request buildPut (String path ) {
118171 return buildPut (path , Maps .newHashMap ());
119172 }
120173
121- /**
122- * put请求,返回request对象
123- *
124- * @param path 请求路径
125- * @param headers 请求头
126- * @return request对象
127- */
128174 public Request buildPut (String path , Map <String , String > headers ) {
129- RequestBody requestBody = RequestBody .create (MediaType .parse ("application/json; charset=utf-8" ), "" );
175+ RequestBody requestBody =
176+ RequestBody .create (MediaType .parse ("application/json; charset=utf-8" ), "" );
130177 return buildPut (path , requestBody , headers );
131178 }
132179
133- /**
134- * post请求,返回request对象
135- *
136- * @param path 请求路径
137- * @param requestBody 请求报文体
138- * @param headers 请求头
139- * @return request对象
140- */
141180 public Request buildPut (String path , RequestBody requestBody , Map <String , String > headers ) {
142181 String url = buildUrl (path );
143- return new Request .Builder ().url (url ).headers (Headers .of (getAllHeaders (headers ))).put (requestBody ).build ();
182+ return new Request .Builder ()
183+ .url (url )
184+ .headers (Headers .of (getAllHeaders (headers )))
185+ .put (requestBody )
186+ .build ();
144187 }
145188
146- /**
147- * delete请求,返回request对象
148- *
149- * @param path 请求路径
150- * @param headers 请求头
151- */
152189 public Request buildDelete (String path , Map <String , String > headers ) {
153190 String url = buildUrl (path );
154- return new Request .Builder ().url (url ).headers (Headers .of (getAllHeaders (headers ))).delete ().build ();
191+ return new Request .Builder ()
192+ .url (url )
193+ .headers (Headers .of (getAllHeaders (headers )))
194+ .delete ()
195+ .build ();
155196 }
156197
157- /**
158- * delete请求,返回request对象
159- *
160- * @param path 请求路径
161- * @param requestBody 请求体
162- * @param headers 请求头
163- * @return request对象
164- */
165198 public Request buildDelete (String path , RequestBody requestBody , Map <String , String > headers ) {
166199 String url = buildUrl (path );
167- return new Request .Builder ().url (url ).headers (Headers .of (getAllHeaders (headers ))).delete (requestBody ).build ();
200+ return new Request .Builder ()
201+ .url (url )
202+ .headers (Headers .of (getAllHeaders (headers )))
203+ .delete (requestBody )
204+ .build ();
168205 }
169206
170- /**
171- * 生成json形式请求报文体,返回请求报文体
172- *
173- * @param data 请求数据对象
174- * @return json形式请求报文体
175- */
176207 public RequestBody getJsonRequest (Object data ) {
177- return RequestBody .create (MediaType .parse ("application/json; charset=utf-8" ), JsonUtil .toJson (data ));
208+ return RequestBody .create (
209+ MediaType .parse ("application/json; charset=utf-8" ), JsonUtil .toJson (data ));
178210 }
179211
180212 public String encode (String parameter ) throws UnsupportedEncodingException {
@@ -189,5 +221,4 @@ private Map<String, String> getAllHeaders(Map<String, String> headers) {
189221 headers .putAll (SdkEnv .getSdkHeader ());
190222 return headers ;
191223 }
192-
193224}
0 commit comments