我正在 Spring Boot 中制作應用程式。在我讓它異步之前它作業得很好。我沒有收到任何錯誤,也沒有 json 回應。我想不通。我該如何解決這個問題。請幫我弄清楚。
帖子存盤庫:
@Repository
public interface PostRepository extends JpaRepository<Post,Long> {
@Async
Post findBySubject(String subject);
}
郵政服務:
@Service
@Transactional
public class PostService {
@Autowired
private PostRepository postRepository;
@Async
public CompletableFuture<Post> find(String subject) throws ExecutionException,
InterruptedException {
System.out.println("Current Thread Name: " Thread.currentThread().getName());
Post post = postRepository.findBySubject(subject);
System.out.println("Current Thread Name: " Thread.currentThread().getName());
return CompletableFuture.completedFuture(post);
}
}
后控制器:
@Slf4j
@RestController
@RequestMapping("/posts")
public class PostController {
@Autowired
private PostService postService;
@GetMapping
public CompletableFuture<Post> get(@RequestParam String subject){
try {
System.out.println("Current Thread Name: " Thread.currentThread().getName());
return postService.find(subject);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
uj5u.com熱心網友回復:
Jpa 存盤庫不是異步的
@Async Post findBySubject(String subject); }
這導致了問題。
如果你想讓它作業,那么你需要回傳 CompletableFuture 。這里我指的是來自堆疊溢位的鏈接:https ://stackoverflow.com/a/38421923/11928455 (但同樣不推薦)
因此,從存盤庫中洗掉 @Async。JpaRepository 不會異步作業。如果您需要異步存盤庫,請改為查看 spring 反應存盤庫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426707.html
