Introduction to feign client of spring cloud

Jiedao jdon 2021-05-04 15:49:13
introduction feign client spring cloud


In this tutorial , We will understand FeignClient And how to Spring Boot/Spring Cloud Use it in your application .

FeignClient It's a declaratively created REST API Client library . therefore , If we don't write remote by hand API client , It's possible to use it Springs RestTemplate, While using Feign It's convenient to declare client definitions , The rest is generated at run time for use .

We're going to build a small command line application , It mimics our Kanban API The complete test of . The sample application will create a new user , Sign in , Retrieve all boards and log off the user again . It captures the most common use cases (POST,GET,DELETE + AuthN)

Add dependency

We use... In this tutorial Maven. Because we don't want to mess up the version number , The easiest way is in Maven POM  Medium dependencyManagement Contained in the Spring Cloud Set up .

<dependencyManagement> 
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>  
      <artifactId>spring-cloud-dependencies</artifactId> 
      <version>Finchley.SR1</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Now? , We can use the classic Spring Boot The launcher adds a dependency to Feign:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

Feign Clients use declarative methods to access API. In order to use it , We have to be in our Spring Boot Use... On applications @EnableFeignClients Annotations to enable S​​pring Cloud Support .

@SpringBootApplication
@EnableFeignClients 
public class FeignIntroductionApplication implements ApplicationRunner 
{ //omitted 
}

The next step is to declare the API The interface of . We named it KanbanClient, Because it will provide the ability to call remote API Methods .

@FeignClient(name="KanbanClient", 
             url= "https://kanbanbackend.herokuapp.com/") 
public interface KanbanClient { }

To convert it to Feign client , We have to set up... On the interface @FeignClient notes , And give it a name property , And use url Property to set the remote URL . It supports SpEL, So we can externalize values into property files . We can also use Eureka Use service discovery here , Instead of using URL, If you use Eureka Service discovery , It's just :

@FeignClient("KanbanApp")

KanbanApp It's registered in Eureka The name of the application in the service register , That is, the producer of the other party Srping.application.name=KanbanApp The name of the configuration in .

Next, we will define the methods to be called remotely , Different remote API Corresponding to different interface methods , Need to use Spring MVC Some comments in , These comments are often used in REST Server side @Controller On . They behave in the same way , This is just for REST client .

POST

Add... To the method @PostMapping Annotate and pass parameters in it , Convert the method to POST call . stay PostMapping In note , We've provided relative to in @FeignClient Set on the comment URL The endpoint of ( Specifically URL route ).

@PostMapping(value = "/register")
String registerUser(User user);

The user is a simple POJO, With user name and password fields .Feign,Spring Will automatically convert it to JSON.

GET

The principle is the same as above , But we use it in a way that @GetMapping. We also sent the authentication header .API Use X-Auth-Token.

@GetMapping("/boards")
List<Board> listBoards(
  @RequestHeader("X-Auth-Token") 
  String authHeader
);

 /boards Will return a list of all the Kanban for the user .Board yes POJO, Contains only id and name.

PUT

Again , This time just use @PutMapping notes .

@PutMapping("/board/{id}")
Board changeBoard(
  @RequestHeader("X-Auth-Token") String authHeader, 
  @PathVariable("id") Long id, 
  Board board
);

We can do this by PUT Submit the endpoint of Kanban (/ board / {id}) Change the name of kanban . For path variables, please refer to the calling with variables section below .

DELETE

It only needs @DeleteMapping notes .

@DeleteMapping("/unregister")
ResponseEntity<Void> unregisterUser(
  @RequestHeader("X-Auth-Token") String authToken, 
  Confirmation user
);

This endpoint needs to have a user password Confirmation Object to delete the account , And if it's successful, it needs to return 200.

Call with variables

If our endpoint needs to be based on something like ids Variables of such entities , We can use... On method parameters @PathVariable notes . Its behavior and Spring MVC @Controllers identical .

Then you can go to @PutMapping Use defined variables such as :

@PutMapping("/board/{id}") 
Board changeBoard(
  @RequestHeader("X-Auth-Token") String authHeader, 
  @PathVariable("id") Long id, 
  Board board
);

Call... Through authentication

We'll use the login endpoint . It requires user credentials to be sent as basic authentication , And the token will be returned for further authentication . When we successfully call / login At the end , It will return in the response header auth token :

@PostMapping("/login")
ResponseEntity<Void> loginUser(
  @RequestHeader("Authorization") String authHeader
);

The first way to pass additional information down is to add something with @RequestHeader Comment method parameters . The value of the parameter will be set to... Defined in the comment HTTP Header value .

In the case of Authentication , It is Authorization header . As a value , We give it basic auth Encoded string .

In the following Kanban API in call , We're going to use... With a token X-Auth-Token header .

The response header cannot be returned directly as a method return value , But we can use Spring Of ResponseEntity, It's a response wrapper . Because our endpoint doesn't return anything in the response body , Therefore, it is necessary to Void As a parameterized type .

When on Kanban API Use in Spring Session when , Need to pass through X-Auth-Token Header exchange auth token .

To retrieve the value we call :

String token = response.getHeaders().getFirst("X-Auth-Token");

Other authentication methods

We can always use... On every method @RequestHeader Comment passing authentication header . however , There's also an alternative to being specified globally .

image Spring MVC equally ,Feign There's an interceptor concept , Can be used to perform specific operations before a remote call . The entry point is RequestInterceptor Interface .

Use Spring, We just need to provide one Bean To achieve Spring Context specific interface , It will be used automatically .

@Bean 
AuthInterceptor authFeign() { 
  return new AuthInterceptor(); 
}
class AuthInterceptor implements RequestInterceptor { 
  @Override 
  public void apply(RequestTemplate template) { 
    template.header("Authorization", "<your token>"); 
  }
}

Our interceptor is a Spring Bean, So we can use Spring And will authN Externalizing information into attributes , Even from the conversational scope of bean Search it in , We'll save information for each user .

Use FeignClient

Now? , We can be like any other Spring Bean The same will KanbanClient Into our code . When it starts ,Spring Cloud Will set up for us Feign Client and provide us with regular Spring Proxy, So that we can simply start using the remote side .

We use Feign The client code in the end looks like this :

@FeignClient(name="KanbanClient", 
             url= "https://kanbanbackend.herokuapp.com/")
public interface KanbanClient {
  @PostMapping(value = "/register") 
  String registerUser(User user); 
  @DeleteMapping("/unregister")
  ResponseEntity<Void> unregisterUser(
    @RequestHeader("X-Auth-Token") String authToken, 
    Confirmation user
  );
  @PostMapping("/login") 
  ResponseEntity<Void> loginUser(
    @RequestHeader("Authorization") String authHeader
  );
  @GetMapping("/boards")
  List<Board> listBoards(
    @RequestHeader("X-Auth-Token") String authHeader
  );
  @PostMapping("/boards") 
  Board createBoard(
    @RequestHeader("X-Auth-Token") String authHeader,
    Board board
  );
  @PutMapping("/board/{id}")
  Board changeBoard(
    @RequestHeader("X-Auth-Token") String authHeader, 
    @PathVariable("id") Long id,
    Board board
  );
}

Complete source code stay GitHub On

版权声明
本文为[Jiedao jdon]所创,转载请带上原文链接,感谢
https://javamana.com/2021/05/20210504154434703w.html

  1. Help, Java how to get all the current processes of the system
  2. Has anyone ever used JMeter or written tests in httpUnit????
  3. Living in a mountain village in late spring
  4. Partridge day, spring of HKUST
  5. JavaScript异步编程4——Promise错误处理
  6. 海康摄像SDK开发笔记(一):海康威视网络摄像头SDK介绍与模块功能
  7. JavaScript asynchronous programming 4 -- promise error handling
  8. Haikang video SDK development notes (1): introduction and module functions of Hikvision webcam SDK
  9. JOP:用于FPGA的嵌入式实时系统中的Java优化处理器内核
  10. Spring Boot源码:使用MongoDB MongoTemplate公开REST在几分钟内实现CRUD功能
  11. Spring Boot应用程序事件教程 - reflectoring
  12. 带有Resilience4j断路器的Spring云网关 - rome
  13. 经验分享:Apache Kafka的缺点与陷阱 - Emil Koutanov
  14. 通过Spring Boot Webflux实现Reactor Kafka
  15. 从Java 8升级到Java 11应该注意的问题
  16. Jop: Java optimized processor core for FPGA embedded real time system
  17. Spring boot source code: use mongodb mongotemplate to open rest to realize crud function in a few minutes
  18. Spring boot application event tutorial - reflecting
  19. Spring cloud gateway with resilience4j circuit breaker - ROM
  20. Experience sharing: shortcomings and pitfalls of Apache Kafka - Emil koutanov
  21. Realization of reactor Kafka through spring boot Webflux
  22. RPC框架设计----Socket与I/0模型
  23. Problems in upgrading from Java 8 to Java 11
  24. RPC framework design -- socket and I / 0 model
  25. RPC框架设计----I/0模型
  26. RPC framework design: I / 0 model
  27. RPC框架设计----NIO编程缓冲区Buffer
  28. RPC框架设计----NIO编程缓冲区Buffer
  29. RPC framework design -- NiO programming buffer
  30. RPC framework design -- NiO programming buffer
  31. Java多线程基础
  32. Java multithreading Foundation
  33. 码农飞升记-00-Java发展历程
  34. Development history of coder-00-java
  35. 码农飞升记-00-Java发展历程
  36. Development history of coder-00-java
  37. Spring and Autumn Moon
  38. Node.js与Spring Boot比较? - Ryan Gleason
  39. Spring WebFlux的明显陷阱 - ŁukaszKyć
  40. Spring创始人Rod大叔对YAML的真实想法
  41. Compare node.js with spring boot- Ryan Gleason
  42. Obvious pitfalls of spring Webflux- Ł ukaszKy ć
  43. Spring founder uncle rod's real thoughts on yaml
  44. 码农飞升记-02-OracleJDK是什么?OracleJDK的版本怎么选择?
  45. What is manong feisheng-02-oracle JDK? How to choose the version of Oracle JDK?
  46. Spring tide surging Xinanjiang
  47. Linux内核软中断
  48. Linux kernel soft interrupt
  49. Linux内核软中断
  50. Linux kernel soft interrupt
  51. Java multithreading Foundation
  52. The construction of Maven private library nexus
  53. I / O stream in Java
  54. JDK 16:Java 16的新功能 - InfoWorld
  55. 在Java中本地进行线程间数据传输的三种方式和源码展示
  56. jdon导致cpu 99%最后tomcat死掉---banq给予回复
  57. 用领域事件模拟AOP注入
  58. JDK 16: new function of Java 16 - InfoWorld
  59. Cartoon: from JVM lock to redis distributed lock
  60. Spring 3.1 终于加入了Cache支持