Feign client for microservice communication¶
Feign is a declarative web service client that simplifies the implementation of communication between microservices.^[001-TODO__code-getway.md]
In a typical Spring Boot architecture, Feign abstracts the complexity of making HTTP requests to other services.^[001-TODO__code-getway.md] Developers define an interface annotated with @FeignClient, and the framework automatically generates the implementation at runtime.^[001-TODO__code-getway.md] This eliminates the need for developers to manually write boilerplate code involving HttpClient or RestTemplate to connect to services like "plt-basics".^[001-TODO__code-getway.md]
Configuration¶
A Feign client is configured via the @FeignClient annotation on a Java interface^[001-TODO__code-getway.md]. This annotation specifies metadata required to locate and communicate with the remote service, such as the service name or a hard-coded url (e.g., ${feign.client.plt-basics.url})^[001-TODO__code-getway.md].
Customization is achieved through the configuration parameter, which allows for the injection of specific beans or interceptors^[001-TODO__code-getway.md]. Common configurations include:
- Interceptors: Classes like
InternalFeignInterceptorcan be added to modify request headers (e.g., adding authentication tokens) before the request is sent^[001-TODO__code-getway.md]. - Support Configs: Classes like
FeignSupportConfigcan be used to set specific encoder or decoder behaviors^[001-TODO__code-getway.md].
Usage¶
The interface defines the specific HTTP endpoints available on the remote service using standard Spring MVC annotations^[001-TODO__code-getway.md].
@FeignClient(contextId = "plt-basics", name = "plt-basics", url = "${feign.client.plt-basics.url}", configuration = {InternalFeignInterceptor.class, FeignSupportConfig.class})
public interface BasicsFeignClient {
@PostMapping("/v1/report")
SuccessResp<Void> createReportRecord(@RequestBody Map<String, String> dto);
@GetMapping(value = "/v1/report/download", consumes = MediaType.APPLICATION_PROBLEM_JSON_VALUE)
SuccessResp<ReportDocumentVo> getDocument(@RequestParam ReportType reportType, @NotNull @RequestParam Long id);
}
Service classes, such as ReportManageDomainServiceImpl, inject this interface and use it to invoke methods on the remote service as if it were a local method call^[001-TODO__code-getway.md].
Sources¶
^[001-TODO__code-getway.md]