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()));

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM