@FeignClient 的使用

 

 添加依赖   
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

 

启用Feign
@EnableFeignClients

 

使用示例:注可以作为调用三方接口的统一入口
@FeignClient(value = "base")
//@FeignClient(name = "labelPrintClient", url = "${boton.printUrl}")
//@FeignClient(name = ClientUrl.ELN_SERVICE,configuration = FeignConfig.class)
public interface BaseFeignService {
    @GetMapping(value = "/user/name/{userId}")
    RestResponse<String> getUserName(@PathVariable Long userId);
}

 

增加拦截方式1:
复制代码
@Aspect
@Component
public class FeignInterceptor {

    @Around("@within(feign))")
    public Object around(ProceedingJoinPoint point, FeignClient feign) throws Exception {
        Object obj = null;
        try {
            obj = point.proceed();
        } catch (Throwable e) {
            error( e.getMessage() , point, feign);
        }
        // 匹配并校验响应结果
        checkResult( obj, point,  feign);
        return obj;
    }

    public static void checkResult(Object obj,ProceedingJoinPoint point, FeignClient feign) throws Exception {
        if (null!=obj) {
            if(obj instanceof RestResponse){
                RestResponse response = (RestResponse)obj;
                if(response.getCode()!=0){
                    error( response.getResult() , point, feign);
                }
            }else {
                JSONObject jsonObj = JSONUtil.parseObj(obj);
                Integer code = jsonObj.getInt("code");
                if(code!=0){
                    error( jsonObj.get("result") , point, feign);
                }
            }
        }
    }

    /** api调用异常 / api正常响应:失败场景 */
    public static void error(Object cause , ProceedingJoinPoint point, FeignClient feign) throws Exception {
        throw new Exception(
                new StringBuffer()
                        .append(feign.value()).append(" 服务调用异常:").append(cause)
                        .append(";Api方法名:").append(point.getSignature().getName())
                        .append(";Api参数:" ).append(ArrayUtil.toString(point.getArgs()))
                        .toString()
        );
    }

} 
复制代码

 

增加拦截方式2:只有请求的拦截
复制代码
@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求Spring信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取请求体
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        // 获取Header、或参数等
        String token = request.getHeader("Authorization");
        //添加token
        requestTemplate.header("Authorization",token);
    }
}
复制代码

 

 


posted on   cc-cf  阅读(2071)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示