java - 请求一个地址,如果失败,则隔30秒请求一次,直到失败10次,就不调用了,如何实现?
PHPz
PHPz 2017-04-17 16:28:34
0
7
681

目前想到的方法是,数据库记录请求的信息(包含请求地址,和错误次数,是否成功),然后用quartz每隔30秒筛选一次数据库没有成功的回调,执行回调。但是我感觉一直跑着定时任务会不会很浪费。

想知道有没有更好的解决方案。

PHPz
PHPz

学习是最好的投资!

reply all(7)
刘奇

If this request fails, you need to judge the url http code

黄舟

That’s it. I can’t think of any better way than this

Ty80

In fact, the title already abstractly explains the implementation.
The question is what problem does this requirement solve?

左手右手慢动作

Loop 10 times for each request. If it succeeds, just break out. Is it necessary to use the database?
How to judge failure:
Set the timeout to 30s. No response for 30s is a failure. Others can be judged by yourself based on the returned httpCode and the returned data content.
How to time a request every 30s:
Record the start of each request. time, when the judgment fails, check whether the current time and the request start time are 30s apart. If 30s has been reached, directly perform the loop request, otherwise use Thread.sleep (30-interval) to sleep the thread, and continue the request after getting up.


If you want to do batch operations, Quartz is fine. If you don’t want to use Quartz, you can also use ScheduledThreadPoolExecutor. Timer is not recommended.
If you want to reduce complexity, you can use this method of retrying a single task.

Ty80

It can also be implemented on the front end, using JQuery’s AJAX asynchronous request

$.ajax({
    url : 'someurl',
    type : 'POST',
    data :  ....,   
    tryCount : 0,
    retryLimit : 3, <!-- 此处就是你失败后尝试再次访问请求的次数-->
    success : function(json) {
        //do something
    },
    error : function(xhr, textStatus, errorThrown ) {
        if (textStatus == 'timeout') {
            this.tryCount++;
            if (this.tryCount <= this.retryLimit) {
                //try again
                $.ajax(this);
                return;
            }            
            return;
        }
        if (xhr.status == 500) {
            //handle error
        } else {
            //handle error
        }
    }
});
刘奇

Java also has its own timer, try using a timer

迷茫

I want to know what the business scenario is like. If I loop 10 times, I will break after judging the success

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template