Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize automatic downgrade of Spring Cloud Feign

Shulou Source: shulou.com Published: 2022-06-01 05:53:23 09月29日 Update

This article mainly explains "how to achieve automatic downgrade in Spring Cloud Feign". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve automatic downgrade in Spring Cloud Feign".

Automatic demotion purpose

When Spring Cloud uses feign, you need to specify the fallback policy explicitly, otherwise an error will be prompted. Let's take a look at what the default feign service requires. Feign service defines a class for factory and fallback

@ FeignClient (value = ServiceNameConstants.UMPS_SERVICE, fallbackFactory = RemoteLogServiceFallbackFactory.class)

PublicinterfaceRemoteLogService {}

But in most cases, our feign downgrade strategy is simple to ensure idempotency, just output the error log. Similar to the following code, it is very inconvenient to develop in an enterprise

@ Slf4j

@ Component

PublicclassRemoteLogServiceFallbackImplimplementsRemoteLogService {

@ Setter

PrivateThrowable cause

@ Override

Public R saveLog (SysLog sysLog,Stringfrom) {

Log.error ("feign failed to insert log", cause)

Returnnull

}

}

Automatic downgrade effect

@ FeignClient (value = ServiceNameConstants.UMPS_SERVICE)

PublicinterfaceRemoteLogService {}

Feign Service completes the same degraded error output

There is no need to define useless fallbackFactory in FeignClient

FallbackFactory also does not need to register with the Spring container

Code change to remove the downgrade factory specified by FeignClient

Code changes, delete downgrade-related code

Core source code

1. Inject our personalized Feign

@ Configuration

@ ConditionalOnClass ({HystrixCommand.class,HystrixFeign.class})

ProtectedstaticclassHystrixFeignConfiguration {

@ Bean

@ Scope (ConfigurableBeanFactory.SCOPE_PROTOTYPE)

@ ConditionalOnProperty ("feign.hystrix.enabled")

PublicFeign.Builder feignHystrixBuilder (FeignContext feignContext) {

ReturnPigxHystrixFeign.builder (feignContext)

.decode404 ()

.errorDecoder (newPigxFeignErrorDecoder ())

}

}

2. The PigxHystrixFeign.target method is the process of generating a proxy class based on the @ FeignClient annotation. Note the comments.

@ Override

Public T target (Target target) {

Class targetType = target.type ()

FeignClient feignClient = AnnotatedElementUtils.getMergedAnnotation (targetType,FeignClient.class)

String factoryName = feignClient.name ()

SetterFactory setterFactoryBean = this.getOptional (factoryName, feignContext,SetterFactory.class)

If (setterFactoryBean! = null) {

This.setterFactory (setterFactoryBean)

}

/ / the following is to obtain the downgrade policy code and build the downgrade. Here, the non-empty check of the demotion is removed.

Class fallback = feignClient.fallback ()

If (fallback! = void.class) {

Return targetWithFallback (factoryName, feignContext, target,this, fallback)

}

Class fallbackFactory = feignClient.fallbackFactory ()

If (fallbackFactory! = void.class) {

Return targetWithFallbackFactory (factoryName, feignContext, target,this, fallbackFactory)

}

Return build () newInstance (target)

}

3. Build feign client to execute PigxHystrixInvocationHandler enhancements

Feign build (@ NullablefinalFallbackFactory nullableFallbackFactory) {

Super.invocationHandlerFactory ((target, dispatch)->

NewPigxHystrixInvocationHandler (target, dispatch, setterFactory, nullableFallbackFactory))

Super.contract (newHystrixDelegatingContract (contract))

Returnsuper.build ()

}

4. PigxHystrixInvocationHandler.getFallback () gets the downgrade policy

@ Override

@ Nullable

@ SuppressWarnings ("unchecked")

ProtectedObject getFallback () {

/ / if @ FeignClient does not have a downgrade policy configured, create one using a dynamic proxy

If (fallbackFactory = = null) {

Fallback = PigxFeignFallbackFactory.INSTANCE.create (target.type (), getExecutionException ())

} else {

/ / if @ FeignClient configures the downgrade policy, use the configured

Fallback = fallbackFactory.create (getExecutionException ())

}

}

5. PigxFeignFallbackFactory.create dynamic agent logic

Public T create (finalClass type,finalThrowable cause) {

Return (T) FALLBACK_MAP.computeIfAbsent (type, key-> {

Enhancer enhancer = newEnhancer ()

Enhancer.setSuperclass (key)

Enhancer.setCallback (newPigxFeignFallbackMethod (type, cause))

Return enhancer.create ()

});

}

6. PigxFeignFallbackMethod.intercept, the default downgrade logic, outputs downgrade method information and error messages, and sets the error format

PublicObject intercept (Object o Magnum method method,Object [] objects,MethodProxy methodProxy) {

Log.error ("Fallback class: [{}] method: [{}] message: [{}]"

Type.getName (), method.getName (), cause.getMessage ()

If (R.classrooms = method.getReturnType ()) {

Final R result = cause instanceofPigxFeignException?

((PigxFeignException) cause) .getResult (): R.builder ()

.code (CommonConstants.FAIL)

.msg (cause.getMessage ()) .build ()

Return result

}

Returnnull

}

Thank you for your reading, the above is the content of "how to achieve automatic downgrade of Spring Cloud Feign". After the study of this article, I believe you have a deeper understanding of how to achieve automatic downgrade of Spring Cloud Feign, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Policy error code agent learning output configuration information content dynamics situation method log logic change personality enterprise customer client container Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn MariaDB Xiaomi Shulou Technology Microsoft