在springboot中跟踪API调用的响应时间
问题描述:
我正在追踪API调用的响应时间。 然后,我想绘制一个图形上的调用响应时间(GET,PUT,POST DELETE),然后比较时间差异。在springboot中跟踪API调用的响应时间
这是我目前正在做的,以找到GET调用的响应时间,但我不太确定它是否正确。
@RequestMapping(value="/Students", method = RequestMethod.GET)
public ResponseEntity<List<Students>> getStudents()
{
long beginTime = System.currentTimeMillis();
List<Students> students = (List<Students>) repository.findAll();
if(students.isEmpty())
{
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
long responseTime = System.currentTimeMillis() - beginTime;
logger.info("Response time for the call was "+responseTime);
return new ResponseEntity(students, HttpStatus.OK);
}
我相信我返回响应时间之前,我的数据实际上返回给客户端这是这整点,但我不能够把它return语句后,因为这将是无法访问码。
有没有更好的方法来追踪通话时间?
答
你可以使用SpringBoot的Around Advice和建议你可以记录时间。它的工作方式是一旦向控制器发出呼叫,Around Around会拦截并启动计时器(记录所用时间)。从建议我们继续使用jointPoint.proceed()方法的主控制器。一旦控制器返回值,您可以记录定时器值。返回对象。
下面是示例代码:
在build.grale包括
compile("org.aspectj:aspectjweaver:1.8.8")
创建组件类和周围@Aspect
@Component
@Aspect
public class advice{
@Around(("@annotation(logger)")
public Object loggerAspect(ProceedingJoinPoint joinPoint){
// start the Timer
Object object = jointPoint.proceed();
// log the timer value
return object;
}
}
把添加注解@Logger在控制器方法。你已准备好出发。
希望这会有所帮助。
你可以参考link的完整说明。
[如何记录Spring Boot中Rest服务所花的时间?](https://stackoverflow.com/questions/42857658/how-to-log-time-taken-by-rest-web-弹簧服务启动) – Vasan
使用Spring Boot Actuator,它将记录指标。你可以流到Grafana之类的东西(其他选项当然可用)。 –
嗨@ M.Deinum,谢谢你的回复。从春季出口指标的最佳方法是什么,以便我可以在grafana上将其可视化?我无法将其导出到influxdb中,我不确定这是否是最好的方法,或者是 – mvantastic