The background,

When using Spring Cloud recently, we found that when we use Feign to call other microservices, when we have multiple Feign clients (e.g. user microservices, commodity microservices), we can configure different implementations for each Feign client. For example: User microservices use Feign’s default contract, while commodity microservices can use Spring MVC’s contract format. How does this work? Let’s write a simple example to simulate this.

Second, the demand for

Suppose we have an interface of CommonApi. The user microservice and our caller implement this interface respectively and realize different functions. However, our product microservice does not implement this interface and adopts the caller’s implementation by default.

The caller (parent context) implements the CommonApi, implemented in the back pocket, if the called does not implement this, otherwise the called uses its own logic. The user microservice (subcontext) implements the CommonApi. The Product microservice (subcontext) does not implement the CommonApi.Copy the code

In the caller, CommonApi in user microservice and Product microservice will be called at the same time. When the called implements CommonApi, its own logic will be used; if the called does not implement CommonApi, its own logic will be used.

This is what we want to achieve:

1. In the caller program, the CommonApi obtained in its own context is implemented by the caller itself.

2. In the caller program, the CommonApi obtained in the context of using the user service is the user service implementation.

3. In the caller program, the CommonApi obtained in the context of the commodity service is implemented by the caller because the commodity service is not implemented by itself.

If we think of CommonApi as Feign in Feign, then in user services we modify Feign’s default Contract, and product services are the default Contract used.

Three, implementation steps

1. Basic code writing

2. Test results

Four, small eggs

Implementation of parent context in Spring Cloud OpenFeign.

FeignContext implements the NamedContextFactory interface, NamedContextFactory in a org. Springframework. Cloud. Context. Named. NamedContextFactory# createContext method, can be seen is how to build a parent-child context.

Complete code

Code link: gitee.com/huan1993/sp…