In this series of previous article, demonstrate how to use Hystrix’s circuit breaker function. In this article, I will demonstrate how to use OpenFeign to simplify the development of the Rest client.
OpenFeign is a calling library for the service consumer in spring cloud. It is usually used in combination with ribbon, hystrix, etc., to simplify the code and configuration of accessing services.
Create a new microservice project
Create a new ordinary maven project in IDEA, name its groupId: cn.com.hohistar.tutorial and artifactId: springcloud-openfeign-client, and then replace the pom.xml of the project with the following:
1 |
|
New data class
Create a new package named: cn.com.hohistar.cloud.model in src/main/java, and add a class named: Todo in it, the code is as follows:
1 |
|
Because all service returns are not standardized to the format of ApiResult, it is also necessary to add the definition of the ApiResult class in the model package. code show as below:
1 |
|
Create Feign instance
Create a new package named: cn.com.hohistar.cloud.service in src/main/java, and then create a new interface in the package named: TodoClient. The code is as follows:
1 | "cloud-todo-service") (value = |
Create a Rest API
Create a new package named: cn.com.hohistar.cloud.api in src/main/java, and then create a new class in the package named: FeignClientApi:
1 |
|
Create application startup class
Create a new class named: FeignClientApplication in the package cn.com.hohistar.cloud as the startup class, the code is as follows:
1 |
|
Add configuration information to the application
Create a new configuration file named application.yml in src/main/resource and add the following content:
1 | server: |
Run program inspection results
After launching the application, visit with a browser:
1 | http://localhost:9091/f/todo |
You can see similar results:
1 | {"succ":true,"code":null,"msg":null,"data":[{"id":1,"title":"Call Metting","desc":""},{"id":2,"title":"Print File","desc":""},{"id":3,"title":"Call Metting","desc":""},{"id":4,"title":"Print File","desc":""}]} |
Add fuse function
Add the dependency library for hystrix in the pom.xml file。
1 | <dependency> |
Add the following training information in application.xml to allow fusing
1 | feign: |
In order to use the custom fallback method, you need to modify the TodoClient interface as follows:
1 |
|