Pablo Fernandez
Pablo Fernandez

Reputation: 287410

How can I insert a delay on every request on a Spring Boot application?

I need to test how my client application will behave when the server is far away and the connection is not great. The client is a JavaFX application using Spring's RestTemplate and the server is a RESTful Spring Boot application.

How can I artificially inject a delay on every request the server gets?

Upvotes: 0

Views: 5867

Answers (1)

Nur Zico
Nur Zico

Reputation: 2447

You can add a HandlerInterceptor which override preHandle and postHandle method.

preHandle will be invoked before request go to Controller.

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception

postHandle will be invoked after completing Controller's method.

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception

Any of the method you can use Thread.sleep() to delay request/response.

You have to extend WebMvcConfigurerAdapter in which you can attach the HandlerInterceptor for servlet

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(MyHandlerInterceptor);
}

Upvotes: 1

Related Questions