@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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个简单的使用 `@FeignClient` 的示例: 假设你有一个名为 `UserService` 的微服务,它提供了一个 `/users/{id}` 的 RESTful API,返回指定用户 ID 的用户信息。现在你想在另一个微服务中调用这个 API,可以使用 `@FeignClient`。 首先,在你的 Maven 或 Gradle 项目中添加以下依赖: ```xml <!-- Maven --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.5.RELEASE</version> </dependency> ``` ```groovy // Gradle implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:2.2.5.RELEASE' ``` 然后,创建一个接口,使用 `@FeignClient` 注解指定要调用的微服务名称和 URL: ```java @FeignClient(name = "user-service", url = "${user-service.url}") public interface UserServiceClient { @GetMapping("/users/{id}") User getUserById(@PathVariable("id") Long id); } ``` 在这里,我们使用Spring 的占位符 `${user-service.url}`,它会从配置文件中读取 `user-service.url` 的值,以便动态设置要调用的 URL。 最后,在你的 Spring Boot 应用程序中使用 `@Autowired` 自动装配 `UserServiceClient` 并调用它的方法即可。 ```java @RestController public class MyController { @Autowired private UserServiceClient userServiceClient; @GetMapping("/users/{id}") public User getUserById(@PathVariable("id") Long id) { return userServiceClient.getUserById(id); } } ``` 这样,当你访问 `/users/{id}` 时,就会调用 `UserService` 微服务的 `/users/{id}` API 并返回用户信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值