yangys
2024-03-27 e48aa2ac8dea1be5db11c63edf0b912c4ad5ce65
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
package com.qianwen.core.http;
 
import java.io.IOException;
import java.util.function.Predicate;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
 
/* loaded from: blade-starter-http-9.3.0.0-SNAPSHOT.jar:org/springblade/core/http/RetryInterceptor.class */
public class RetryInterceptor implements Interceptor {
    private final RetryPolicy retryPolicy;
 
    public RetryInterceptor(RetryPolicy retryPolicy) {
        this.retryPolicy = retryPolicy;
    }
 
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        RetryTemplate template = createRetryTemplate(this.retryPolicy);
        return (Response) template.execute(context -> {
            Response response = chain.proceed(request);
            Predicate<ResponseSpec> respPredicate = this.retryPolicy.getRespPredicate();
            if (respPredicate == null)
                return response;
            ResponseBody body = response.peekBody(Long.MAX_VALUE);
            try (HttpResponse httpResponse = new HttpResponse(response)) {
                if (respPredicate.test(httpResponse))
                    throw new IOException("Http Retry ResponsePredicate test Failure.");
            }
            return response.newBuilder().body(body).build();
        });
    }
 
    private static RetryTemplate createRetryTemplate(RetryPolicy policy) {
        RetryTemplate template = new RetryTemplate();
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(policy.getMaxAttempts());
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(policy.getSleepMillis());
        template.setRetryPolicy(retryPolicy);
        template.setBackOffPolicy(backOffPolicy);
        return template;
 
    }
}