• FeignClient接口封装


    Feign是一种声明式、模块化的HTTP客户端。在SpringCloud中使用Feign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样,开发者完全无感知在进行HTTP请求调用。

    1.接口定义
    首先在单独的module中定义接口:

    @FeignClient(name ="com.johar.feign-test", path ="/user", url="${account-service-endpoint}")

    public interface User {

    @GetMapping("/{userId}")

    public BaseResponsefindById(@PathVariable("userId")int userId);

    @PostMapping("/add")
    

    public BaseResponsecreateUser(@RequestBody UserDto userDto);

    }

    FeignClient常用的注解属性如下:

    (1)name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现。

    (2)url:一般用于调试,手动指定@FeignClient的调用地址。

    (3)path:定义当前的FeignClient的统一前缀。

    (4)configuration:Feign的配置类,可以自定义Feign的Encoder,Decode,LogLevel,Contract。

    (5)fallbckFactory:实现每个接口通用的容错逻辑,减少重复代码。

    2.实现定义的接口
    在另外一个module中实现定义的接口:

    @RestController

    @RequestMapping("/user")

    public class UserControllerimplements User {

    @GetMapping("/{userId}")

    @Override

    public BaseResponsefindById(@PathVariable("userId")int userId) {
    

    UserDto userDto = UserDto.builder().age(29).id(userId).name("johar").sex(1).build();

        BaseResponse result =new BaseResponse();
    
        result.setData(userDto);
    
        return result;
    
    }
    

    @PostMapping("/add")

    @Override

    public BaseResponsecreateUser(@RequestBody UserDto userDto) {
    

    userDto.setId(1);

        BaseResponse result =new BaseResponse();
    
        result.setData(userDto);
    
        return result;
    
    }
    

    }

    3.使用FeignClient调用接口

    3.1 引入接口包

    org.springframework.cloud

    spring-cloud-starter-netflix-ribbon

    com.johar

    feign-api

    0.0.1-SNAPSHOT

    3.2 在启动类开启FeignClients

    @EnableFeignClients(basePackages = "com.johar.feignapi")

    3.3 FeignClient接口调用

    @SpringBootApplication

    @EnableFeignClients(basePackages ="com.johar.feignapi")

    public class FeignClientApplicationimplements CommandLineRunner {

    public static void main(String[] args) {

    SpringApplication.run(FeignClientApplication.class, args);

    }
    

    @Autowired

    private Useruser;
    
    @Override
    
    public void run(String... args)throws Exception {
    

    System.out.println(user.findById(1));

        System.out.println(user.createUser(UserDto.builder().sex(2).name("Anna").age(28).build()));
    
    }
    

    }

  • 相关阅读:
    线段树 建树 单点修改 单点/区间查询
    JAVAEE学期总结
    Spring框架教程IDEA版-----更新中
    第一章操作系统引论-------批处理、分时、实时各个操作系统特点 进程与线程的区别
    读《阿法狗围棋系统的简要分析》
    matlab启动后的默认路径
    从长辈们的故事谈起
    在成为一名老司机的路上不要狂奔
    物理学与其它科学的关系
    读《现象级带货网红的自我修养》
  • 原文地址:https://www.cnblogs.com/Johar/p/12489785.html
Copyright © 2020-2023  润新知