Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Spring cloud (4): the Application of Feign

Shulou Source: shulou.com Published: 2022-06-03 05:37:21 09月23日 Update

1. Concept

Feign is a declarative, templated HTTP client that declares a web service client, which makes it easier to write a web service client.

2. Application

2.1. in a project, modules and modules need to call each other. For example, if the web module needs to call the services of the service module, you need to introduce Fegin into web to create a project web-fegin.

2.2. add to the pom file

Org.springframework.cloud

Spring-cloud-starter-feign

2.3.Create the startup class WebFeignApplication

@ SpringBootApplication

@ EnableDiscoveryClient

@ EnableFeignClients (basePackages= "com.web")

Public class WebFeignApplication {

Public static void main (String [] args) {

SpringApplication.run (FeignApplication.class, args)

}

}

2.4.Defining service interface class UserFeignClient

@ FeignClient (name = WebConstants.SERVIE_USER_NAME)

Public interface UserFeignClient {

@ RequestMapping ("/ {id}")

Public User findByIdFeign (@ RequestParam ("id") Long id)

}

2.5.Call Fegin in the web layer

@ RestController

Public class FeignController {

@ Autowired

Private UserFeignClient userFeignClient

@ GetMapping ("feign/ {id}")

Public User findByIdFeign (@ PathVariable Long id) {

User user = this.userFeignClient.findByIdFeign (id)

Return user

}

}

2.6 if you do not use the fegin above, you will have to write a service invocation class to invoke the service service, which increases the difficulty of programming. Now that you have fegin, there is no need to repeat the wheel.

3. Configuration of application.properties

Spring.application.name=web-fegin

Server.port=8020

Eureka.client.serviceUrl.defaultZone= http://localhost:9411/eureka/

Service.user.name=microservice-provider-user

4. Define the constant WebConstants

Public class WebConstants {

Public static final String SERVIE_USER_NAME= "${service.user.name}"

}

5. Visit

Http://127.0.0.1:8020/fegin/1

6. Summary:

In fact, the HTTP invocation service method is encapsulated through Feign, allowing the client to invoke the method directly as if it were a local method.

Tags: Services customers clients modules methods projects applications necessary between constants interfaces files time concepts templates wheels difficulty faceted encapsulation programming Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info vpn Linux MariaDB NVidia