我在一个发送授权请求的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未经授权:[no body]&;。例如,我可以从4个可调用的作业中接收4个令牌5次,并在第6次尝试时得到错误。
如果我将线程数更改为2,那么我的错误次数就会减少。每次有10个线程失败
并且它在Postman中总是工作得很好。
我怎样才能理解问题的原因?
变化
authHeaders.set("Grant_type", "password");
authHeaders.set("Authorization", "password");