当前位置:   article > 正文

spring boot 中 open feign接口拦截实现_openfeign 捕获异常 统一处理

openfeign 捕获异常 统一处理

如何实现调用其他服务默认添加请求参数,包括feign调用?

实现OncePerRequestFilter接口

OncePerRequestFilter接口就是每次发起请求,确保只会执行一次。

  • 自定义创建会话上下文 MyRequestContext.java,可以在我们需要的时候就直接拿出来使用,请求结束就应该清除对象
public class MyRequestContext {
    public static final String USER_ID = "user_id";
    public static final String ACCESS_TOKEN = "accessToken";
    public static final String PROTOCOL_SCHEME = "Protocol-Scheme";
    
    private static final ThreadLocal<Map<String, Object>> USER_LOCAL = new InheritableThreadLocal<Map<String, Object>>();

    private MyRequestContext() {
    }

    public static Object get(String key) {
        return ((Map)USER_LOCAL.get()).get(key);
    }
    
    public static void put(String key, Object value) {
        ((Map)USER_LOCAL.get()).put(key, value);
    }

    public static void remove() {
        USER_LOCAL.remove();
    }

    public static Map<String, Object> getAll() {
        return (Map)USER_LOCAL.get();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 过滤器中维护上下文 MyRequestContext.java

public class RequestLinkContextFilter extends OncePerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(RequestLinkContextFilter.class);

    public RequestLinkContextFilter() {
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String userId = request.getHeader("user_id");
        if (StringUtils.isNotBlank(userId)) {
            MyRequestContext.put("user_id", Long.parseLong(userId));
        }
        String accessToken = request.getHeader("accessToken");
        if (StringUtils.isNotBlank(accessToken)) {
            MyRequestContext.put("accessToken", accessToken);
        }

        String protocolScheme = request.getHeader("Protocol-Scheme");
        if (StringUtils.isNotBlank(protocolScheme)) {
            MyRequestContext.put("Protocol-Scheme", protocolScheme);
        }

        String originFrom = request.getHeader("origin-from");
        if (StringUtils.isNotBlank(originFrom)) {
            MyRequestContext.put("origin-from", originFrom);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            MyRequestContext.remove();
        }

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

feign调用也需要实现传递参数

  • 实现接口RequestInterceptor.java
public class MyFeignInterceptor implements RequestInterceptor {
    public MyFeignInterceptor() {
    }

    public void apply(RequestTemplate template) {
        Map<String, Object> allContext = MyRequestContext.getAll();
        if (!MapUtils.isEmpty(allContext)) {
            Iterator var3 = allContext.entrySet().iterator();

            while(var3.hasNext()) {
                Entry<String, Object> entry = (Entry)var3.next();
                if (entry.getValue() instanceof String) {
                    template.header((String)entry.getKey(), new String[]{entry.getValue().toString()});
                } else {
                    template.header((String)entry.getKey(), new String[]{JSON.toJSONString(entry.getValue())});
                }
            }

        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

RestTemplate(Ribbon)拦截器

  • 实现接口ClientHttpRequestInterceptor.java

public class MyHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    public MyHttpRequestInterceptor() {
    }

    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        Map<String, Object> allContext = MyRequestContext.getAll();
        if (MapUtils.isEmpty(allContext)) {
            return execution.execute(request, body);
        } else {
            Iterator var6 = allContext.entrySet().iterator();

            while(var6.hasNext()) {
                Entry<String, Object> entry = (Entry)var6.next();
                if (!headers.containsKey(entry.getKey())) {
                    if (entry.getValue() instanceof String) {
                        headers.add((String)entry.getKey(), entry.getValue().toString());
                    } else {
                        headers.add((String)entry.getKey(), JSON.toJSONString(entry.getValue()));
                    }
                }
            }

            return execution.execute(request, body);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

加入spring容器即可生效

拦截总结

springMVC项目,网页请求拦截

  • HandlerInterceptor

HandlerInterceptor是最常规的,其拦截的http请求是来自于客户端浏览器之类的,是最常见的http请求拦截器

  • 使用案例

public class LoginFilter extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(),request.getRequestURI());
		//request.getHeader(String) 从请求头中获取数据
		//从请求头中获取用户token
		Long userId= getUserId(request.getHeader("H-User-Token"));
		if (userId != null && checkAuth(userId,request.getRequestURI())){
			return true;
		}
		//这里的异常是我自定义的异常,系统抛出异常后框架捕获异常然后转为统一的格式返回给前端, 其实这里也可以返回false
		throw new FastRuntimeException(20001,"No access");
	}

	private Long getUserId(String userToken){
		Long userId = null;
		return userId;
	}

	private boolean checkAuth(Long userId,String requestURI){
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

springBoot项目,RestTemplate/Ribbon请求拦截

  • ClientHttpRequestInterceptor

ClientHttpRequestInterceptor是对RestTemplate的请求进行拦截的,在项目中直接使用restTemplate.getForObject的时候,会对这种请求进行拦截,经常被称为:RestTempalte拦截器或者Ribbon拦截器;

OpenFeign调用拦截

  • RequestInterceptor

RequestInterceptor常被称为是Feign拦截器,由于Feign调用底层实际上还是http调用,因此也是一个http拦截器,在项目中使用Feign调用的时候,可以使用此拦截器

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/84596
推荐阅读
相关标签
  

闽ICP备14008679号