Loss of ThreadLocal Information in OpenFeign with Resilience4j Circuit Breaker
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 25/100
Línea de trabajo
Empieza leyendo FeignCircuitBreakerInvocationHandler#asSupplier y Resilience4JCircuitBreakerFactory#configureExecutorService, que son los dos puntos de extensión descritos. Compara su comportamiento en cuanto a la propagación del contexto y aclara la API compatible antes de implementar nada. Se considerará terminado cuando exista un enfoque acordado para conservar la información de ThreadLocal de la solicitud durante la ejecución asíncrona del circuit breaker sin filtrarla entre tareas.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Is your feature request related to a problem? Please describe.
Issue Summary:
I encountered an issue while using Spring Cloud OpenFeign. When configuring circuit breaking (resilience4j), the FeignCircuitBreakerInvocationHandler submits our Feign client to be processed by an asynchronous thread, resulting in the loss of ThreadLocal information in the request context. Do you have any suggestions for resolving this issue?
Business Scenario:
In a Spring Web project, we have a custom RequestInterceptor that retrieves information stored in ThreadLocal before making a request. This information is used to populate RequestHeader and is then passed to downstream services. However, after introducing resilience4j as a circuit breaker in OpenFeign, resilience4j executes requests in a thread pool, causing ThreadLocal information to be lost.
Describe the solution you'd like
Proposal:
Therefore, I propose adding a hook (template method) within the org.springframework.cloud.openfeign.FeignCircuitBreakerInvocationHandler#asSupplier method in OpenFeign. This hook would allow the application service to retrieve the ThreadLocal object and, within the Supplier, set the ThreadLocal to the executing thread's ThreadLocal, similar to how it is done with RequestContextHolder. Is this approach feasible?
Below is sample code, assuming SubjectContext is a hook
private Supplier<Object> asSupplier(final Method method, final Object[] args) {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
final Thread caller = Thread.currentThread();
// Sample code
**SubjectContext context = SubjectContext.getContext();**
return () -> {
boolean isAsync = caller != Thread.currentThread();
try {
if (isAsync) {
RequestContextHolder.setRequestAttributes(requestAttributes);
**SubjectContext.setContext(context);**
}
return dispatch.get(method).invoke(args);
}
catch (RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
finally {
if (isAsync) {
RequestContextHolder.resetRequestAttributes();
**SubjectContext.clear();**
}
}
};
}
Describe alternatives you've considered
I have also considered using a hook provided by resilience4j during application startup, specifically within org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory#configureExecutorService. By passing a custom thread pool object here, I could potentially propagate the ThreadLocal information. Sample code is as follows:
@Configurable
@AllArgsConstructor
public class CircuitBreakerConfiguration implements ApplicationRunner {
private final Resilience4JCircuitBreakerFactory factory;
@Override
public void run(ApplicationArguments args) throws Exception {
ContextThreadPoolExecutor contextThreadPoolExecutor =
new ContextThreadPoolExecutor(2, 5, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1024));
// **change ThreadPoolExecutor**
factory.configureExecutorService(contextThreadPoolExecutor);
}
public static class ContextThreadPoolExecutor extends ThreadPoolExecutor {
public ContextThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public void execute(Runnable command) {
super.execute(wrap(command));
}
private static Runnable wrap(Runnable runnable) {
**SubjectContext context = SubjectContext.getContext();**
return () -> {
**SubjectContext.setContext(context);**
try {
runnable.run();
} finally {
**SubjectContext.clear();**
}
};
}
}
}
However, I find it less elegant, and I believe resolving it within the asSupplier() method of OpenFeign would be more versatile and applicable to a broader range of scenarios.
Additional context
spring-cloud-openfeign-3.1.2
- Lenguaje dominante
- Java
- Estrellas
- 1.3k
- Forks
- 835
- Merge medio
- 23 h 57 min
- PR fusionados (30 d)
- 25
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de spring-cloud/spring-cloud-openfeign
-
question
Dificultad 4/5 3-5 días Aptitud para principiantes 35/100
spring-cloud/spring-cloud-openfeign#1392 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
FeignClientsConfiguration$MicrometerConfiguration.class cannot be opened because it does not existAbiertofeedback-provided
Dificultad 4/5 3-5 días Aptitud para principiantes 35/100
spring-cloud/spring-cloud-openfeign#1379 · 5 comentarios ·
Los mantenedores suelen responder en 1 día
-
waiting-for-triage
Dificultad 3/5 1-2 días Aptitud para principiantes 57/100
spring-cloud/spring-cloud-openfeign#1344 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
waiting-for-triage
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
spring-cloud/spring-cloud-openfeign#1343 ·
Los mantenedores suelen responder en 1 día
-
waiting-for-triage
Dificultad 3/5 1-2 días Aptitud para principiantes 45/100
spring-cloud/spring-cloud-openfeign#1340 · 1 comentario ·
Los mantenedores suelen responder en 1 día
Todos los issues de spring-cloud/spring-cloud-openfeign
Issues similares
-
Dificultad 1/5 Menos de una hora Aptitud para principiantes 75/100
521xueweihan/HelloGitHub#4105 ·
-
Awaiting further input from submitter
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
-
Regression in 5.9.0: CuratorCache fails with ClassCastException when the client is not a CuratorFrameworkBasePosiblemente ocupada @sftwnd la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
Los mantenedores suelen responder en 1 día