我在发送身份验证请求的 Spring Boot 应用程序中使用 Callable 接口:
public class TestCallable implements Callable<TestDto> {
TestEntity testEntity;
public TestCallable(TestEntity testEntity) {
this.testEntity = testEntity;
}
@Override
public TestDto call() throws Exception {
String authRequestBody = "{" +
"\"username\": \"" + testEntity.getLogin() + "\"," +
"\"password\": \"" + testEntity.getPassword() + "\"," +
"\"client_id\": \"" + testEntity.getClientId() + "\"," +
"\"client_secret\": \"" + testEntity.getClientSecret() + "\"" +
"}";
HttpHeaders authHeaders = new HttpHeaders();
authHeaders.setContentType(MediaType.APPLICATION_JSON);
authHeaders.set("Accept", "application/json");
authHeaders.set("Grant_type", "password");
HttpEntity<String> authEntity = new HttpEntity<String>(authRequestBody, authHeaders);
RestTemplate restTemplate = new RestTemplate();
TestDto testDto = testDto = restTemplate.postForObject(testEntity.getEndpoint(), authEntity, TestDto.class);
return testDto;
}
}
我在 4 个线程中发送这些请求:
List<Future<TestDto>> futuresList = new ArrayList<Future<TestDto>>();
ExecutorService pool = Executors.newFixedThreadPool(4);
for (Integer i=0; i<4; i++) {
Callable<TestDto> callable = new TestCallable(testEntity);
Future<TestDto> future = pool.submit(callable);
futuresList.add(future);
}
问题是有时我会收到错误“401 Unauthorized: [no body]”。例如,我可以从 4 个可调用作业中收到 4 个令牌 5 次,并在第 6 次尝试时得到错误。
如果我将线程数更改为 2,那么我出现错误的频率就会降低。每次有 10 个线程失败。
它在 Postman 中总是可以正常工作。
我如何了解问题的原因?