Search in sources :

Example 36 with TimeLimiter

use of io.github.resilience4j.timelimiter.TimeLimiter in project resilience4j by resilience4j.

the class TimeLimiterInterceptor method intercept.

@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
    Optional<AnnotationValue<io.github.resilience4j.micronaut.annotation.TimeLimiter>> opt = context.findAnnotation(io.github.resilience4j.micronaut.annotation.TimeLimiter.class);
    if (!opt.isPresent()) {
        return context.proceed();
    }
    ExecutableMethod executableMethod = context.getExecutableMethod();
    final String name = executableMethod.stringValue(io.github.resilience4j.micronaut.annotation.TimeLimiter.class).orElse("default");
    TimeLimiter timeLimiter = this.timeLimiterRegistry.timeLimiter(name);
    InterceptedMethod interceptedMethod = InterceptedMethod.of(context);
    try {
        switch(interceptedMethod.resultType()) {
            case PUBLISHER:
                return interceptedMethod.handleResult(fallbackReactiveTypes(Flowable.fromPublisher(interceptedMethod.interceptResultAsPublisher()).compose(TimeLimiterTransformer.of(timeLimiter)), context));
            case COMPLETION_STAGE:
                return interceptedMethod.handleResult(fallbackForFuture(timeLimiter.executeCompletionStage(executorService, () -> {
                    try {
                        return interceptedMethod.interceptResultAsCompletionStage();
                    } catch (Exception e) {
                        throw new CompletionException(e);
                    }
                }), context));
            case SYNCHRONOUS:
                try {
                    return timeLimiter.executeFutureSupplier(() -> CompletableFuture.supplyAsync(context::proceed));
                } catch (Throwable exception) {
                    return fallback(context, exception);
                }
            default:
                return interceptedMethod.unsupported();
        }
    } catch (Exception e) {
        return interceptedMethod.handleException(e);
    }
}
Also used : TimeLimiter(io.github.resilience4j.timelimiter.TimeLimiter) ExecutableMethod(io.micronaut.inject.ExecutableMethod) InterceptedMethod(io.micronaut.aop.InterceptedMethod) CompletionException(java.util.concurrent.CompletionException) CompletionException(java.util.concurrent.CompletionException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue)

Example 37 with TimeLimiter

use of io.github.resilience4j.timelimiter.TimeLimiter in project resilience4j by resilience4j.

the class TimeLimiterChain method execute.

@Override
public void execute(Chain chain) throws Exception {
    String prefix = chain.getRegistry().get(Resilience4jConfig.class).getEndpoints().getTimelimiter().getPath();
    chain.prefix(prefix, chain1 -> {
        chain1.get("events", ctx -> Promise.<TimeLimiterEventsEndpointResponse>async(d -> {
            List<TimeLimiterEventDTO> eventsList = eventConsumerRegistry.getAllEventConsumer().stream().flatMap(CircularEventConsumer::getBufferedEventsStream).sorted(Comparator.comparing(TimeLimiterEvent::getCreationTime)).map(TimeLimiterEventDTO::createTimeLimiterEventDTO).collect(Collectors.toList());
            d.success(new TimeLimiterEventsEndpointResponse(eventsList));
        }).then(r -> ctx.render(Jackson.json(r))));
        chain1.get("stream/events", ctx -> {
            Flux<TimeLimiterEvent> eventStreams = Flux.fromIterable(timeLimiterRegistry.getAllTimeLimiters()).flatMap(timeLimiter -> ReactorAdapter.toFlux(timeLimiter.getEventPublisher()));
            Function<TimeLimiterEvent, String> data = r -> Jackson.getObjectWriter(chain1.getRegistry()).writeValueAsString(TimeLimiterEventDTO.createTimeLimiterEventDTO(r));
            ServerSentEvents events = ServerSentEvents.serverSentEvents(eventStreams, e -> e.id(TimeLimiterEvent::getTimeLimiterName).event(c -> c.getEventType().name()).data(data));
            ctx.render(events);
        });
        chain1.get("events/:name", ctx -> {
            String timeLimiterName = ctx.getPathTokens().get("name");
            Promise.<TimeLimiterEventsEndpointResponse>async(d -> {
                List<TimeLimiterEventDTO> eventsList = eventConsumerRegistry.getEventConsumer(timeLimiterName).getBufferedEventsStream().sorted(Comparator.comparing(TimeLimiterEvent::getCreationTime)).map(TimeLimiterEventDTO::createTimeLimiterEventDTO).collect(Collectors.toList());
                d.success(new TimeLimiterEventsEndpointResponse(eventsList));
            }).then(r -> ctx.render(Jackson.json(r)));
        });
        chain1.get("stream/events/:name", ctx -> {
            String timeLimiterName = ctx.getPathTokens().get("name");
            TimeLimiter timeLimiter = timeLimiterRegistry.getAllTimeLimiters().stream().filter(tL -> tL.getName().equals(timeLimiterName)).findAny().orElseThrow(() -> new IllegalArgumentException(String.format("time limiter with name %s not found", timeLimiterName)));
            Function<TimeLimiterEvent, String> data = r -> Jackson.getObjectWriter(chain1.getRegistry()).writeValueAsString(TimeLimiterEventDTO.createTimeLimiterEventDTO(r));
            ServerSentEvents events = ServerSentEvents.serverSentEvents(ReactorAdapter.toFlux(timeLimiter.getEventPublisher()), e -> e.id(TimeLimiterEvent::getTimeLimiterName).event(c -> c.getEventType().name()).data(data));
            ctx.render(events);
        });
        chain1.get("events/:name/:type", ctx -> {
            String timeLimiterName = ctx.getPathTokens().get("name");
            String eventType = ctx.getPathTokens().get("type");
            Promise.<TimeLimiterEventsEndpointResponse>async(d -> {
                List<TimeLimiterEventDTO> eventsList = eventConsumerRegistry.getEventConsumer(timeLimiterName).getBufferedEventsStream().sorted(Comparator.comparing(TimeLimiterEvent::getCreationTime)).filter(event -> event.getEventType() == TimeLimiterEvent.Type.valueOf(eventType.toUpperCase())).map(TimeLimiterEventDTO::createTimeLimiterEventDTO).collect(Collectors.toList());
                d.success(new TimeLimiterEventsEndpointResponse(eventsList));
            }).then(r -> ctx.render(Jackson.json(r)));
        });
        chain1.get("stream/events/:name/:type", ctx -> {
            String timeLimiterName = ctx.getPathTokens().get("name");
            String eventType = ctx.getPathTokens().get("type");
            TimeLimiter timeLimiter = timeLimiterRegistry.getAllTimeLimiters().stream().filter(rL -> rL.getName().equals(timeLimiterName)).findAny().orElseThrow(() -> new IllegalArgumentException(String.format("time limiter with name %s not found", timeLimiterName)));
            Flux<TimeLimiterEvent> eventStream = ReactorAdapter.toFlux(timeLimiter.getEventPublisher()).filter(event -> event.getEventType() == TimeLimiterEvent.Type.valueOf(eventType.toUpperCase()));
            Function<TimeLimiterEvent, String> data = r -> Jackson.getObjectWriter(chain1.getRegistry()).writeValueAsString(TimeLimiterEventDTO.createTimeLimiterEventDTO(r));
            ServerSentEvents events = ServerSentEvents.serverSentEvents(eventStream, e -> e.id(TimeLimiterEvent::getTimeLimiterName).event(c -> c.getEventType().name()).data(data));
            ctx.render(events);
        });
    });
}
Also used : Function(ratpack.func.Function) ReactorAdapter(io.github.resilience4j.reactor.adapter.ReactorAdapter) TimeLimiterEvent(io.github.resilience4j.timelimiter.event.TimeLimiterEvent) TimeLimiterRegistry(io.github.resilience4j.timelimiter.TimeLimiterRegistry) Promise(ratpack.exec.Promise) Collectors(java.util.stream.Collectors) Resilience4jConfig(io.github.resilience4j.ratpack.Resilience4jConfig) Jackson(ratpack.jackson.Jackson) ServerSentEvents(ratpack.sse.ServerSentEvents) Chain(ratpack.handling.Chain) Inject(javax.inject.Inject) Flux(reactor.core.publisher.Flux) List(java.util.List) TimeLimiterEventDTO(io.github.resilience4j.common.timelimiter.monitoring.endpoint.TimeLimiterEventDTO) TimeLimiter(io.github.resilience4j.timelimiter.TimeLimiter) CircularEventConsumer(io.github.resilience4j.consumer.CircularEventConsumer) TimeLimiterEventsEndpointResponse(io.github.resilience4j.common.timelimiter.monitoring.endpoint.TimeLimiterEventsEndpointResponse) Action(ratpack.func.Action) Comparator(java.util.Comparator) EventConsumerRegistry(io.github.resilience4j.consumer.EventConsumerRegistry) TimeLimiter(io.github.resilience4j.timelimiter.TimeLimiter) TimeLimiterEventDTO(io.github.resilience4j.common.timelimiter.monitoring.endpoint.TimeLimiterEventDTO) Resilience4jConfig(io.github.resilience4j.ratpack.Resilience4jConfig) TimeLimiterEventsEndpointResponse(io.github.resilience4j.common.timelimiter.monitoring.endpoint.TimeLimiterEventsEndpointResponse) ServerSentEvents(ratpack.sse.ServerSentEvents) TimeLimiterEvent(io.github.resilience4j.timelimiter.event.TimeLimiterEvent) List(java.util.List)

Aggregations

TimeLimiter (io.github.resilience4j.timelimiter.TimeLimiter)37 Test (org.junit.Test)31 TimeLimiterRegistry (io.github.resilience4j.timelimiter.TimeLimiterRegistry)9 Duration (java.time.Duration)7 ThreadPoolBulkhead (io.github.resilience4j.bulkhead.ThreadPoolBulkhead)4 CircuitBreaker (io.github.resilience4j.circuitbreaker.CircuitBreaker)4 Counter (io.micrometer.core.instrument.Counter)4 ContextAwareScheduledThreadPoolExecutor (io.github.resilience4j.core.ContextAwareScheduledThreadPoolExecutor)3 TimeLimiterConfig (io.github.resilience4j.timelimiter.TimeLimiterConfig)3 TimeLimiterEvent (io.github.resilience4j.timelimiter.event.TimeLimiterEvent)3 DefaultEventConsumerRegistry (io.github.resilience4j.consumer.DefaultEventConsumerRegistry)2 TestThreadLocalContextPropagatorWithHolder (io.github.resilience4j.test.TestContextPropagators.TestThreadLocalContextPropagatorWithHolder)2 List (java.util.List)2 TimeoutException (java.util.concurrent.TimeoutException)2 Awaitility.matches (com.jayway.awaitility.Awaitility.matches)1 Awaitility.waitAtMost (com.jayway.awaitility.Awaitility.waitAtMost)1 Bulkhead (io.github.resilience4j.bulkhead.Bulkhead)1 BulkheadFullException (io.github.resilience4j.bulkhead.BulkheadFullException)1 Cache (io.github.resilience4j.cache.Cache)1 CallNotPermittedException (io.github.resilience4j.circuitbreaker.CallNotPermittedException)1