You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中Controller调用Service耗时占比过高问题咨询

Spring Boot调用链路中Controller到Service的耗时疑惑

我在Spring Boot中搭建了一套基础的Rest Controller->Service->Repository调用链路,调试各环节耗时后发现:总耗时60ms,其中Controller调用Service方法(标记//POINT B)耗时30ms,Service调用Repository方法(标记//POINT C)耗时1ms,Repository从数据库返回数据耗时20ms。POINT A到POINT B之间无任何业务逻辑,我疑惑这30ms是否是Spring每次调用Service时需要执行初始化操作导致的,是否存在Spring配置错误。

相关代码

Controller

@Autowired
ContactService contactService;

@RequestMapping(value = "/contact/{contactId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ContactResponse> fetchContactById(@PathVariable Integer contactId) throws Exception {
  ContactResponse contact = new ContactResponse();

  //POINT A
  contact.setContact(contactService.findContactById(contactId));
  .......
  return new ResponseEntity<ContactResponse>(contact, HttpStatus.OK);
}

Service类

@Autowired
ContactRepository contactRepository;

@Service
public class ContactService {

  //POINT B
  public ContactDTO findContactById(Integer contactId) throws Exception {
    return contactRepository.findContactById(contactId);
  }

}

Repository

@Repository
public class ContactRepository {

  //POINT C
  public ContactDTO findContactById(Integer contactId) {
    .......
    return contactDTO;
  }

}

问题分析与排查建议

首先明确:Spring的Service Bean默认是单例模式,应用启动阶段就完成初始化,不会在每次方法调用时重复执行初始化操作,所以这30ms和"每次调用初始化"无关。

可以从以下方向排查耗时原因:

  • 验证计时准确性:确认POINT A到POINT B的计时是否仅统计了方法调用的开销,有没有误包含Service方法内部的逻辑耗时。建议用System.nanoTime()在POINT A前和POINT B第一行分别记录时间,计算精确差值,避免统计误差。
  • 排查AOP代理开销:如果Service类被Spring AOP代理(比如开启了事务、日志、权限校验等切面逻辑),方法调用时会经过代理的拦截逻辑,可能产生额外耗时。可以暂时关闭相关切面(比如注释掉@Transactional注解),重新测试看耗时是否下降。
  • 检查线程上下文切换:如果应用的请求线程池资源不足,请求处理时发生线程上下文切换,也会导致这段调用耗时增加。可以查看Spring Boot的线程池配置,监控请求处理时的线程状态。
  • 确认是否为首次调用开销:如果配置了@Lazy注解,Service Bean会延迟初始化,首次调用时会触发初始化操作,但只会发生一次。可以多次调用接口,观察后续请求的耗时是否下降,如果是,那首次的30ms属于正常的懒加载初始化开销。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:25:17