Spring RestTemplate - 登录请求有时会挂起等待响应
Spring RestTemplate - Log on request sometimes hangs awaiting response
我在 Java 客户端中使用休息模板登录服务器并接收所需的 headers 以将连接升级到安全的 websocket。
这是我的代码:
private static void loginAndSaveJsessionIdCookie(final String user, final String password, final HttpHeaders headersToUpdate) {
String url = "http://localhost:" + port + "/websocket-services/login.html";
new RestTemplate().execute(url, HttpMethod.POST,
new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
System.out.println("start login attempt");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", user);
map.add("password", password);
new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
}
},
new ResponseExtractor<Object>() {
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
System.out.println("got login repsonse");
headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
return null;
}
});
}
这通常有效,但偶尔(尤其是在 websocket 连接超时后)服务器没有响应,我的客户端在方法挂起等待响应时停止响应。
任何人都可以建议修复或解决这个问题吗?因为它会导致客户端完全冻结,需要强行关闭。
异步任何代码线程是最好的方法,您可以使用 ExecutorService
指定您希望的任何超时。根据您的需要,可以使用以下两个选项(请检查 API 以了解它们之间的区别):-
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
或
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
我在 Java 客户端中使用休息模板登录服务器并接收所需的 headers 以将连接升级到安全的 websocket。
这是我的代码:
private static void loginAndSaveJsessionIdCookie(final String user, final String password, final HttpHeaders headersToUpdate) {
String url = "http://localhost:" + port + "/websocket-services/login.html";
new RestTemplate().execute(url, HttpMethod.POST,
new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
System.out.println("start login attempt");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", user);
map.add("password", password);
new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
}
},
new ResponseExtractor<Object>() {
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
System.out.println("got login repsonse");
headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
return null;
}
});
}
这通常有效,但偶尔(尤其是在 websocket 连接超时后)服务器没有响应,我的客户端在方法挂起等待响应时停止响应。
任何人都可以建议修复或解决这个问题吗?因为它会导致客户端完全冻结,需要强行关闭。
异步任何代码线程是最好的方法,您可以使用 ExecutorService 指定您希望的任何超时。根据您的需要,可以使用以下两个选项(请检查 API 以了解它们之间的区别):-
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
或
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;