Java @事务处理大大降低了RESTAPI的速度
服务从构造函数中的DB获取数据,并将其存储在Java @事务处理大大降低了RESTAPI的速度,java,rest,spring-boot,spring-data,Java,Rest,Spring Boot,Spring Data,服务从构造函数中的DB获取数据,并将其存储在HashMap中,然后从HashMap返回数据。请看一看: @RestController @RequestMapping("/scheduler/api") @Transactional(readOnly = true, transactionManager = "cnmdbTm") public class RestApiController { private final Set<String> cache; @A
HashMap
中,然后从HashMap
返回数据。请看一看:
@RestController
@RequestMapping("/scheduler/api")
@Transactional(readOnly = true, transactionManager = "cnmdbTm")
public class RestApiController {
private final Set<String> cache;
@Autowired
public RestApiController(CNMDBFqdnRepository cnmdbRepository, CNMTSFqdnRepository cnmtsRepository) {
cache = new HashSet<>();
cache.addAll(getAllFqdn(cnmdbRepository.findAllFqdn()));
cache.addAll(getAllFqdn(cnmtsRepository.findAllFqdn()));
}
@RequestMapping(value = "/fqdn", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public List<SchedulerRestDto> checkFqdn(@RequestBody List<SchedulerRestDto> queryList) throws ExecutionException {
for (SchedulerRestDto item : queryList) {
item.setFound(1);
if (!cache.contains(item.getFqdn())) {
item.setFound(0);
}
}
return queryList;
}
private Set<String> getAllFqdn(List<String> fqdnList) {
Set<String> result = new HashSet<>();
for (String fqdn : fqdnList) {
result.add(fqdn);
}
return result;
}
}
之后,服务在不到100毫秒的时间内返回结果
我认为它与DB有关,但我不知道如何修复它
有什么想法吗?经过几个小时的实验,我意识到主要原因是课堂上的注释@Transactional 当我在一个方法上移动这个注释时,服务返回的响应更快。在我的最终决定中,我将此注释移动到另一个类。新构造函数是
@Autowired
public RestApiController(FqdnService fqdnService, SqsService sqsService) {
Objects.requireNonNull(fqdnService);
cache = fqdnService.getCache();
}
代码更干净,没有任何性能问题
@Autowired
public RestApiController(FqdnService fqdnService, SqsService sqsService) {
Objects.requireNonNull(fqdnService);
cache = fqdnService.getCache();
}