引言

记录一下 OkHttp 的使用;OkHttp 异步发送回调请求,增加回调失败重试。

使用 OkHttp 发送回调

/**
 * 回调重试类
 */
@Data
public class CallBackRetryData {
    /**
     * 回调信息JSON
     */
    private JSONObject bodyRequest;
    /**
     * 回调发送地址
     */
    private String url;
    /**
     * 重试次数
     */
    private int time;

    public CallBackRetryData(JSONObject bodyRequest, String url, int time) {
        this.bodyRequest = bodyRequest;
        this.url = url;
        this.time = time;
    }
}

/**
 * HTTP 操作类
 */
@Slf4j
@Service
public class HttpService {
    private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient().newBuilder()
            .connectTimeout(1, TimeUnit.MINUTES)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .build();

    /**
     * 回调重试队列
     */
    private final Queue<CallBackRetryData> VERIFY_QUEUE = new LinkedList<>();

    /**
     * 构造回调信息
     */
    public void buildCallBackData() {
        JSONObject bodyRequest = new JSONObject();
        bodyRequest.put("userId", "123456789");

        CallBackRetryData retryData = new CallBackRetryData(bodyRequest, "https://发送回调地址", 1);
        sendCallBack(retryData);
    }

    /**
     * 异步发送回调
     */
    public void sendCallBack(CallBackRetryData retryData) {
        RequestBody requestBody = RequestBody.create(retryData.getBodyRequest().toJSONString(), MediaType.parse("application/json;charset=utf-8"));
        Request request = new Request.Builder().url(retryData.getUrl()).post(requestBody)
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();

        OK_HTTP_CLIENT.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("[回调失败][call:{}]", e.getMessage());
                // 回调次数+1
                retryData.setTime(retryData.getTime() + 1);
                // 放入验证队列
                VERIFY_QUEUE.offer(retryData);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                CallBackResponseData callBackData = JSONObject.parseObject(responseData, CallBackResponseData.class);
                if (callBackData.getCode() != 200) {
                    log.error("[回调失败][状态码错误:{}]", callBackData);
                    // 回调次数+1
                    retryData.setTime(retryData.getTime() + 1);
                    // 放入验证队列
                    VERIFY_QUEUE.offer(retryData);
                }
            }
        });
    }
	
    /**
     * 每分钟检查一次
     */
	@Scheduled(cron = "0 0/1 * * * ? ")
    public void execute() {
        // 执行超时验证队列
        while (VERIFY_QUEUE.size() > 0) {
            CallBackRetryData retryData = VERIFY_QUEUE.poll();
            
            // 重新发送
            if (retryData.getTime() <= 3) {
                try {
	                log.info("[VERIFY_QUEUE][userId:{}][time:{}]",
	                        retryData.getBodyRequest().getString("userId"),
	                        retryData.getTime());
	                        
                    sendBonusCallBack(retryData);
	            } catch (Exception e) {
	                log.error("[VERIFY_QUEUE error: {}]", e.getMessage());
	            }
            }
            
        }
    }
}

其他

Java OkHttp使用

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部