Spring Cloud integrates OpenFeign, easy RPC

foreword

The Springcloud solution implements microservices; it is a common solution for many small and medium-sized companies to implement microservices; the RPC call between each microservice unit is also the most common scenario through Web Restful implementation in the SpringCloud solution. In the overall solution of Springcloud, the official recommendation is to use SpringCloud OpenFeign to achieve this purpose; many technical forums on this topic have related articles for introduction. In most articles, they have not kept pace with the times. SpringCloud's The version is still in a series of versions named after subway stations launched in 2019, such as Hoxton.SRX, etc.; the 2019 version is too old, and the ribbon and hystrix of netifix are no longer maintained. Today we will give What you introduced is to use the latest SpringCloud2021 series version to integrate OpenFeign to realize RPC.

SpringCloud&SpringBoot

The above picture is the release map of SpringCloud on SpringCloud official website; the latest SpringCloud version is 2021.0.X, pay attention to the second column, since SpringCloud implements and defines interfaces based on the SpringBoot framework, it needs to strictly correspond to SpringCloud and The version of SpringBoot; As shown in the figure above, our SpringBoot can choose to use the 2.6.X series or the 2.7.X series. The author recommends using the 2.6.X series first

SpringCloud OpenFeign

The above picture is excerpted from the homepage of the OpenFeign module on the SpringCloud official website; (https://spring.io/projects/spring-cloud-openfeign)

As shown in the diagram: OpenFeign is a declarative REST client: Feign creates a dynamic implementation of an interface decorated with JAX-RS or Spring MVC annotations REST RPC implementation.

The figure below is the version blueprint of SpringCloud OpenFeign. The author recommends using version 3.1.X, and the author uses version 3.1.1

Spring Cloud OpenFeign workflow

Target (dynamic proxy layer), that is, the interface layer defined by RPC through FeignClient, this technology uses Java's dynamic proxy technology and the Bean life cycle management technology of BeanProcessor in SpringBoot;

Constract is the contract layer. WebMvcContract is implemented in SpringCloud's WebMvc, which is the default contract. This contract is used when no contract is specified; the OpenFeign package implements Feign's standard contract, which is usually not specified in our project development. They all use Mvc contracts. When defining the RPC interface of FeignClient, the annotations used are also MVC annotations, such as: PostMapping, GetMapping

MethodHandler is the specific implementation method of dynamic proxy, which corresponds to the RPC call to Target

Steps for usage

Introducing the OpenFeign package

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

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

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

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

<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-feign</artifactId>
    <version>1.7.0</version>
</dependency>

The startup class introduces Feign support

@SpringBootApplication
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

The @EnableFeignClients annotation needs to be added in the startup class, so that when the project is started, there will be an autoconfiguration mechanism that automatically scans all FeignClients in the Application as the root package path, and produces the Bean objects of the dynamic proxy layer represented in the process steps;

Define the client RPC interface

Define the interface on the client to call the WEB RESTFUL service provided by the service provider;

The client only needs to define the API for access according to the WEB API standard provided by the service provider, and through the access to the client interface, it will be processed to the dynamic proxy layer. The dynamic proxy layer encapsulates the interface in WEB RESTFUL according to the contract, and then In the methodHandler, go to the service provider to make WEB calls through HttpClient, so as to complete the realization of RPC;

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    Page<Store> getStores(Pageable pageable);

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);

    @RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
    void delete(@PathVariable Long storeId);
}

The above are all MVC contracts used, and the annotations used are all MVC annotations; the following example uses Feign’s own standard annotations; the author recommends that this method is more standard

// after Hystrix is removed from SpringCloud2021.0.1, the fallback is ineffective
@FeignClient(name = "${codeman.service.name:codeman}", url = "${codeman.service.address:}", fallback = CodeManFallbackImpl.class)
public interface CodeManFeign extends CodeManService {

    @RequestLine("GET /codeman/info/version")
    public String getVersion();

    @RequestLine("GET /codeman/info/author")
    public String getAuthor();

    @RequestLine("GET /codeman/info/request/{userid}")    //对应请求方式和路径
    public String requestLine(@Param("userid") String userid);
}

call RPC

@Slf4j
@Component("CodeManService")
public class CodeManServiceImpl implements CodeManService {

    @Autowired
    CodeManFeign codeManFeign;

    @Override
    @CircuitBreaker(name = "default", fallbackMethod = "getVersionFallback")
    public String getVersion() {

        return codeManFeign.getVersion();
    }

    @Override
    @CircuitBreaker(name = "default", fallbackMethod = "getAuthorFallback")
    public String getAuthor() {
        return codeManFeign.getAuthor();
    }

    @Override
    @CircuitBreaker(name = "default", fallbackMethod = "requestLineFallback")
    public String requestLine(String userid) {
        return codeManFeign.requestLine(userid);
    }


    public String getVersionFallback(Throwable t) {
        log.info("=================================  Exception(getVersion): {}", t.getMessage());
        return "N/A";
    }

    public String getAuthorFallback(Throwable t) {
        log.info("=================================  Exception(getAuthor): {}", t.getMessage());
        return "SpringCloud";
    }

    public String requestLineFallback(String userid, Throwable t){
        log.info("=================================  Exception(requestLine): {}", t.getMessage());
        return "Kill team‘s poison " + userid;
    }
}


 

conclusion

This article mainly introduces the use of OpenFeign to implement RPC calls in the latest version of springcloud. As a complete OpenFeign RPC call implementation, there are more advanced topics, such as Fallback; , in the future related articles will introduce the advanced usage of these OpenFeign; please continue to pay attention;

Thank you for your continued attention, don't miss the exciting content.

Guess you like

Origin blog.csdn.net/inthirties/article/details/126798773