赞
踩
- @Configuration
- public class CloudServerConfiguration {
-
- @Bean
- public HeaderInterceptor headerInterceptor() {
- //微服务权限拦截处理
- return new HeaderInterceptor();
- }
-
- @Bean
- @ConditionalOnProperty(name = "system.cloud.feign.exception.enabled", havingValue="true", matchIfMissing=true)
- public FeignExceptionAspect feignExceptionAspect() {
- //微服务权限拦截处理
- return new FeignExceptionAspect();
- }
-
- }
- /**
- * Title: FeignExceptionAspect
- * Description: Feign统一异常处理
- */
- @Aspect
- @Order(Ordered.LOWEST_PRECEDENCE - 100)
- public class FeignExceptionAspect {
-
- /**
- * Pointcut注解声明切点
- * 配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点
- * @within 对类起作用,@annotation 对方法起作用
- */
- @Pointcut("@within(org.springframework.cloud.openfeign.FeignClient)")
- public void feignClientPointCut() {}
-
- /**
- * 配置前置通知,使用在方法aspect()上注册的切入点
- * 同时接受JoinPoint切入点对象,可以没有该参数
- * @param joinPoint
- * @throws ClassNotFoundException
- */
- @Around("feignClientPointCut()")
- public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
- Object object = proceedingJoinPoint.proceed();
- if(object instanceof ResponseDTO<?>) {
- ResponseDTO<?> responseDTO = (ResponseDTO<?>)object;
- if(!responseDTO.getCode().equals("10000000")) {
- throw new BusinessException(responseDTO.getCode(), responseDTO.getMessage());
- }
- }
- return object;
-
- }
- }
-
- /**
- * <p>Title: HeaderInterceptor</p>
- * <p>Description: 微服务间调用,免权限校验标志</p>
- *
- * @date 创建时间:2019年7月12日 上午11:31:50
- */
- public class HeaderInterceptor implements RequestInterceptor {
-
- // private static final Logger logger = LoggerFactory.getLogger(HeaderInterceptor.class);
-
- @Override
- public void apply(RequestTemplate requestTemplate) {
- //微服务间调用,免权限校验标志 参见 ScyPermissionAspect
- requestTemplate.header("ignoreScy", "true");
- // 从request取token信息
- ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
- if(servletRequestAttributes == null) {
- return;
- }
- HttpServletRequest request = servletRequestAttributes.getRequest();
- Enumeration<String> headerNames = request.getHeaderNames();
-
- if (headerNames != null) {
- while (headerNames.hasMoreElements()) {
- String name = headerNames.nextElement();
- String value = request.getHeader(name);
- if ("usernameKey".equalsIgnoreCase(name)) {
- requestTemplate.header(name, value);
- }
- if ("appName".equalsIgnoreCase(name)) {
- requestTemplate.header(name, value);
- }
- if ("language".equalsIgnoreCase(name)) {
- requestTemplate.header(name, value);
- }
- }
- }
-
- }
-
- }
在项目中,经常会使用全局异常对代码异常进行捕捉,导致 其他微服务调用 FeignClient 异常会获取不到, 所以 需要做一个全局拦截 ,判断错误 则重新抛出异常
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。