zoukankan      html  css  js  c++  java
  • 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()));
    
    }
    

    }

  • 相关阅读:
    SQLServer2005删除log文件和清空日志的方案
    使用sql语句创建修改SQL Server标识列(即自动增长列)
    C# 使用ffmpeg.exe进行音频转换完整demo-asp.net转换代码
    web页面如何播放amr的音频文件
    IIS7.5 伪静态 脚本映射 配置方法
    多表数据连接 Left join
    .NET 开发快捷键大全
    微信开发-ACCESS TOKEN 过期失效解决方案
    HTML5常用的方法
    IIS 7.0 部署MVC
  • 原文地址:https://www.cnblogs.com/Johar/p/12489785.html
Copyright © 2011-2022 走看看