In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.