我目前正在试验 Vaadin Java 框架,我注意到客户端引擎不会重试向服务器发送请求。当移动互联网网络薄弱或不一致时,最好继续重试发送请求而不是放弃。
有谁知道如何在 Vaadin 中实现这一目标?
最佳答案
扩展 ApplicationConnection 并覆盖 doAjaxRequest 应该足以实现您想要做的事情。像这样的东西:
public class MyApplicationConnection extends ApplicationConnection {
private final Logger logger = Logger
.getLogger(MyApplicationConnection.class.getName());
@Override
protected void doAjaxRequest(final String uri, final JSONObject payload,
final RequestCallback requestCallback) throws RequestException {
// wrap the original request callback handle the retries
RequestCallback myRequestCallback = new RequestCallback() {
private int retries = 3;
@Override
public void onResponseReceived(Request request, Response response) {
int status = response.getStatusCode();
if (status / 100 == 2) { // 2xx Successful
requestCallback.onResponseReceived(request, response);
} else {
handleError(request, response, null);
}
}
@Override
public void onError(Request request, Throwable exception) {
handleError(request, null, exception);
}
private void handleError(Request request, Response response,
Throwable exception) {
if (retries == 0) {
logger.info("Ajax request failed.");
if (response == null) {
requestCallback.onError(request, exception);
} else {
requestCallback.onResponseReceived(request, response);
}
} else {
try {
logger.info("Ajax request failed, retrying " + retries
+ " more times.");
retries--;
MyApplicationConnection.super.doAjaxRequest(uri,
payload, this);
} catch (RequestException e) {
// something went wrong in the ajax send() call, so no
// point in retrying
logger.warning("Sending Ajax request failed. Cause: "
+ e.getMessage());
requestCallback.onError(request, exception);
}
}
}
};
super.doAjaxRequest(uri, payload, myRequestCallback);
}
}
在你的 *.gwt.xml 文件中:
<replace-with class="com.example.client.MyApplicationConnection">
<when-type-is class="com.vaadin.client.ApplicationConnection"/>
</replace-with>
您可能还想在 handleError 方法中添加一个 Timer 或其他东西,这样当网络关闭时,请求将等待一段时间才能恢复。虽然它应该是相当微不足道的。
关于vaadin - 如何强制 Vaadin 客户端引擎重试向服务器发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22962285/