如何configurationspring拦截器来调用每个请求

我想configuration我的弹簧拦截器,以便每个请求应该被调用。

  • 我在API-GATEWAY (Spring-Boot)中使用拦截器,
  • 从API-GATEWAY我打电话给其他微服务。
  • 来自API-GATEWAY的其他微服务的调用工作正常。
  • 我打电话的其他服务是Node.js服务,另一方面,我的API网关是在春季启动。
  • 所有服务(Node.js + Spring-Boot)都在Docker Container上运行。

我在Interceptor中面临一个问题。 我想以这样的方式来configuration它,每个请求都应该被称为preHandle()并执行我写在其中的操作。

我注意到一个我想在这里提到的问题。

如果我正在调用的服务被停止(不运行),拦截器工作正常,给我一个没有findsomename-service的响应。 如果相同的服务正在运行,则拦截器不会执行。

这是我的代码片段

 @EnableEurekaClient @SpringBootApplication @EnableZuulProxy @Configuration public class Application extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private TokenValidateInterceptor tokenValidateInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(tokenValidateInterceptor).addPathPatterns("/**"); } 

拦截器

 @Component public class TokenValidateInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { LOG.info("#### Starting TokenValidateInterceptor.preHandle ####"); String apiKey = null; try { apiKey = request.getHeader("apikey"); LOG.info("The request come with apikey ======" + apiKey); LOG.info("Actual apikey ======" + azureApikey); } 

您必须将此拦截器添加到您的调度程序xml文件中:

 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" p:interceptors-ref="tokenInterceptor" /> <bean id="tokenInterceptor" class="yourpackage.TokenValidateInterceptor" /> </beans> 

这里有几个很好的例子:

  • Spring MVC Interceptot
  • Dzone弹簧拦截器