How to use Feign of Spring Cloud micro-service
Editor to share with you how to use the Feign of Spring Cloud microservices, I believe most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's learn about it!
Feign is a declarative http client with the goal of reducing the complexity of Http API. It can be used to handle calls between microservices.
01
-
Interface module (demo-account)
New API for 1.AccountController
@ GetMapping ("/ {id}") public ResponseEntity getById (@ PathVariable ("id") final long id) {final Account account = service.getById (id); log.info ("getById: [{}]", account); return Rs.ok (account);}
02
-
Feign module (demo-feign)
1. New module demo-feign,pom.xml add dependency
Org.springframework.cloud spring-cloud-starter-openfeign
two。 Create a new AccountService
@ FeignClient (name = "DEMO-ACCOUNT") public interface AccountService {@ GetMapping ("/ demo-account/account/ {id}") ResponseEntity getById (@ PathVariable ("id") final long id);}
The above getById method can directly copy the corresponding controller code, keeping only the user-defined parameters, and pay attention to completing the request path.
The name of @ FeignClient is the name of the called service registered with the registry, that is, eureka.instance.appname, which is usually the value of spring.application.name.
The calling module (demo-feign) controller should be requested in the same way as the called module (demo-account).
3. Create a new controller/AccountController
@ Slf4j@RestController@RequestMapping ("/ account") public class AccountController {@ Resource private AccountService service
@ GetMapping ("/ get-by-id") @ ApiOperation ("get account details through id") public ResponseEntity getById () {final ResponseEntity response = service.getById (1L); final Account account = Rs.requireNonNull (response, ResCode.ACCOUNT_FAIL_GET_BY_ID); return Rs.ok (account);}}
4. Add startup class FeignApplication
@ EnableFeignClients (basePackages = "io.github.ramerf.feign.service") @ EnableDiscoveryClient@SpringBootApplication (scanBasePackages = {"io.github.ramerf.wind", "io.github.ramerf.feign"}) public class FeignApplication {public static void main (String [] args) {SpringApplication.run (FeignApplication.class, args);}}
The basePackages attribute of @ EnableFeignClients, which specifies the package in which the feign interface definition is located.
03
-
Start the module test
Start the demo-eureka,demo-gateway,demo-account,demo-feign module.
Visit: http://localhost:3000/demo-feign/account/get-by-id
The above is all the contents of the article "how to use Feign for Spring Cloud Micro Services". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!