Feign是一種聲明式、模塊化的HTTP客戶端。在SpringCloud中使用Feign,可以做到使用HTTP請(qǐng)求訪問遠(yuǎn)程服務(wù),就像調(diào)用本地方法一樣,開發(fā)者完全無(wú)感知在進(jìn)行HTTP請(qǐng)求調(diào)用。
1.接口定義
首先在單獨(dú)的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的名稱,如果項(xiàng)目使用了Ribbon,name屬性會(huì)作為微服務(wù)的名稱,用于服務(wù)發(fā)現(xiàn)。
(2)url:一般用于調(diào)試,手動(dòng)指定@FeignClient的調(diào)用地址。
(3)path:定義當(dāng)前的FeignClient的統(tǒng)一前綴。
(4)configuration:Feign的配置類,可以自定義Feign的Encoder,Decode,LogLevel,Contract。
(5)fallbckFactory:實(shí)現(xiàn)每個(gè)接口通用的容錯(cuò)邏輯,減少重復(fù)代碼。
2.實(shí)現(xiàn)定義的接口
在另外一個(gè)module中實(shí)現(xiàn)定義的接口:
@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調(diào)用接口
3.1 引入接口包
? <groupId>org.springframework.cloud
? <artifactId>spring-cloud-starter-netflix-ribbon
? <groupId>com.johar
? <artifactId>feign-api
? <version>0.0.1-SNAPSHOT
</dependency>
3.2 在啟動(dòng)類開啟FeignClients
@EnableFeignClients(basePackages = "com.johar.feignapi")
3.3 FeignClient接口調(diào)用
@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()));
? ? }
}