我开始CompletableFuture
在 Spring Boot 中使用,我在某些地方看到通常的存储库方法返回CompletableFuture <Entity>
而不是Entity
.
我不知道发生了什么,但是当我返回CompletableFuture
存储库中的实例时,代码运行完美。但是,当我返回实体时,代码不会异步工作并且总是返回null
.
这是一个例子:
@Service
public class AsyncServiceImpl{
/** .. Init repository instances .. **/
@Async(AsyncConfiguration.TASK_EXECUTOR_SERVICE)
public CompletableFuture<Token> getTokenByUser(Credential credential) {
return userRepository.getUser(credential)
.thenCompose(s -> TokenRepository.getToken(s));
}
}
@Repository
public class UserRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_REPOSITORY)
public CompletableFuture<User> getUser(Credential credentials) {
return CompletableFuture.supplyAsync(() ->
new User(credentials.getUsername())
);
}
}
@Repository
public class TokenRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_REPOSITORY)
public CompletableFuture<Token> getToken(User user) {
return CompletableFuture.supplyAsync(() ->
new Token(user.getUserId())
);
}
}
前面的代码运行完美,但下面的代码不会异步运行,结果总是null
.
@Service
public class AsyncServiceImpl {
/** .. Init repository instances .. **/
@Async(AsyncConfiguration.TASK_EXECUTOR_SERVICE)
public CompletableFuture<Token> requestToken(Credential credential) {
return CompletableFuture.supplyAsync(() -> userRepository.getUser(credential))
.thenCompose(s ->
CompletableFuture.supplyAsync(() -> TokenRepository.getToken(s)));
}
}
@Repository
public class UserRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_REPOSITORY)
public User getUser(Credential credentials) {
return new User(credentials.getUsername());
}
}
@Repository
public class TokenRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_SERVICE)
public Token getToken(User user) {
return new Token(user.getUserId());
}
}
为什么第二个代码不起作用?