Search in sources :

Example 11 with RateLimiter

use of io.github.resilience4j.ratelimiter.RateLimiter in project resilience4j by resilience4j.

the class RateLimiterChain method execute.

@Override
public void execute(Chain chain) throws Exception {
    String prefix = chain.getRegistry().get(Resilience4jConfig.class).getEndpoints().getRateLimiters().getPath();
    chain.prefix(prefix, chain1 -> {
        chain1.get("events", ctx -> Promise.<RateLimiterEventsEndpointResponse>async(d -> {
            List<RateLimiterEventDTO> eventsList = eventConsumerRegistry.getAllEventConsumer().flatMap(CircularEventConsumer::getBufferedEvents).sorted(Comparator.comparing(RateLimiterEvent::getCreationTime)).map(RateLimiterEventDTO::createRateLimiterEventDTO).toJavaList();
            d.success(new RateLimiterEventsEndpointResponse(eventsList));
        }).then(r -> ctx.render(Jackson.json(r))));
        chain1.get("stream/events", ctx -> {
            Seq<Flowable<RateLimiterEvent>> eventStreams = rateLimiterRegistry.getAllRateLimiters().map(rateLimiter -> RxJava2Adapter.toFlowable(rateLimiter.getEventPublisher()));
            Function<RateLimiterEvent, String> data = r -> Jackson.getObjectWriter(chain1.getRegistry()).writeValueAsString(RateLimiterEventDTO.createRateLimiterEventDTO(r));
            ServerSentEvents events = ServerSentEvents.serverSentEvents(Flowable.merge(eventStreams), e -> e.id(RateLimiterEvent::getRateLimiterName).event(c -> c.getEventType().name()).data(data));
            ctx.render(events);
        });
        chain1.get("events/:name", ctx -> {
            String rateLimiterName = ctx.getPathTokens().get("name");
            Promise.<RateLimiterEventsEndpointResponse>async(d -> {
                List<RateLimiterEventDTO> eventsList = eventConsumerRegistry.getEventConsumer(rateLimiterName).getBufferedEvents().sorted(Comparator.comparing(RateLimiterEvent::getCreationTime)).map(RateLimiterEventDTO::createRateLimiterEventDTO).toJavaList();
                d.success(new RateLimiterEventsEndpointResponse(eventsList));
            }).then(r -> ctx.render(Jackson.json(r)));
        });
        chain1.get("stream/events/:name", ctx -> {
            String rateLimiterName = ctx.getPathTokens().get("name");
            RateLimiter rateLimiter = rateLimiterRegistry.getAllRateLimiters().find(rL -> rL.getName().equals(rateLimiterName)).getOrElseThrow(() -> new IllegalArgumentException(String.format("rate limiter with name %s not found", rateLimiterName)));
            Function<RateLimiterEvent, String> data = r -> Jackson.getObjectWriter(chain1.getRegistry()).writeValueAsString(RateLimiterEventDTO.createRateLimiterEventDTO(r));
            ServerSentEvents events = ServerSentEvents.serverSentEvents(RxJava2Adapter.toFlowable(rateLimiter.getEventPublisher()), e -> e.id(RateLimiterEvent::getRateLimiterName).event(c -> c.getEventType().name()).data(data));
            ctx.render(events);
        });
        chain1.get("events/:name/:type", ctx -> {
            String rateLimiterName = ctx.getPathTokens().get("name");
            String eventType = ctx.getPathTokens().get("type");
            Promise.<RateLimiterEventsEndpointResponse>async(d -> {
                List<RateLimiterEventDTO> eventsList = eventConsumerRegistry.getEventConsumer(rateLimiterName).getBufferedEvents().sorted(Comparator.comparing(RateLimiterEvent::getCreationTime)).filter(event -> event.getEventType() == RateLimiterEvent.Type.valueOf(eventType.toUpperCase())).map(RateLimiterEventDTO::createRateLimiterEventDTO).toJavaList();
                d.success(new RateLimiterEventsEndpointResponse(eventsList));
            }).then(r -> ctx.render(Jackson.json(r)));
        });
        chain1.get("stream/events/:name/:type", ctx -> {
            String rateLimiterName = ctx.getPathTokens().get("name");
            String eventType = ctx.getPathTokens().get("type");
            RateLimiter rateLimiter = rateLimiterRegistry.getAllRateLimiters().find(rL -> rL.getName().equals(rateLimiterName)).getOrElseThrow(() -> new IllegalArgumentException(String.format("rate limiter with name %s not found", rateLimiterName)));
            Flowable<RateLimiterEvent> eventStream = RxJava2Adapter.toFlowable(rateLimiter.getEventPublisher()).filter(event -> event.getEventType() == RateLimiterEvent.Type.valueOf(eventType.toUpperCase()));
            Function<RateLimiterEvent, String> data = r -> Jackson.getObjectWriter(chain1.getRegistry()).writeValueAsString(RateLimiterEventDTO.createRateLimiterEventDTO(r));
            ServerSentEvents events = ServerSentEvents.serverSentEvents(eventStream, e -> e.id(RateLimiterEvent::getRateLimiterName).event(c -> c.getEventType().name()).data(data));
            ctx.render(events);
        });
    });
}
Also used : Function(ratpack.func.Function) RxJava2Adapter(io.github.resilience4j.adapter.RxJava2Adapter) RateLimiterEvent(io.github.resilience4j.ratelimiter.event.RateLimiterEvent) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) Promise(ratpack.exec.Promise) Resilience4jConfig(io.github.resilience4j.ratpack.Resilience4jConfig) Jackson(ratpack.jackson.Jackson) ServerSentEvents(ratpack.sse.ServerSentEvents) Chain(ratpack.handling.Chain) Inject(javax.inject.Inject) List(java.util.List) Flowable(io.reactivex.Flowable) CircularEventConsumer(io.github.resilience4j.consumer.CircularEventConsumer) Action(ratpack.func.Action) Seq(io.vavr.collection.Seq) Comparator(java.util.Comparator) EventConsumerRegistry(io.github.resilience4j.consumer.EventConsumerRegistry) RateLimiterRegistry(io.github.resilience4j.ratelimiter.RateLimiterRegistry) Resilience4jConfig(io.github.resilience4j.ratpack.Resilience4jConfig) RateLimiterEvent(io.github.resilience4j.ratelimiter.event.RateLimiterEvent) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) ServerSentEvents(ratpack.sse.ServerSentEvents) List(java.util.List) Flowable(io.reactivex.Flowable)

Example 12 with RateLimiter

use of io.github.resilience4j.ratelimiter.RateLimiter in project resilience4j by resilience4j.

the class SemaphoreBasedRateLimiterImplTest method changeDefaultTimeoutDuration.

@Test
public void changeDefaultTimeoutDuration() throws Exception {
    ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class);
    RateLimiter rateLimiter = new SemaphoreBasedRateLimiter("some", config, scheduledExecutorService);
    RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(TIMEOUT);
    then(rateLimiterConfig.getTimeoutDurationInNanos()).isEqualTo(TIMEOUT.toNanos());
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(LIMIT);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(REFRESH_PERIOD);
    then(rateLimiterConfig.getLimitRefreshPeriodInNanos()).isEqualTo(REFRESH_PERIOD.toNanos());
    rateLimiter.changeTimeoutDuration(Duration.ofSeconds(1));
    then(rateLimiterConfig != rateLimiter.getRateLimiterConfig()).isTrue();
    rateLimiterConfig = rateLimiter.getRateLimiterConfig();
    then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ofSeconds(1));
    then(rateLimiterConfig.getTimeoutDurationInNanos()).isEqualTo(Duration.ofSeconds(1).toNanos());
    then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(LIMIT);
    then(rateLimiterConfig.getLimitRefreshPeriod()).isEqualTo(REFRESH_PERIOD);
    then(rateLimiterConfig.getLimitRefreshPeriodInNanos()).isEqualTo(REFRESH_PERIOD.toNanos());
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RateLimiterConfig(io.github.resilience4j.ratelimiter.RateLimiterConfig) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) Test(org.junit.Test)

Example 13 with RateLimiter

use of io.github.resilience4j.ratelimiter.RateLimiter in project resilience4j by resilience4j.

the class RateLimiterExportsTest method testExportsRateLimiterMetrics.

@Test
public void testExportsRateLimiterMetrics() {
    // Given
    final CollectorRegistry registry = new CollectorRegistry();
    final RateLimiter rateLimiter = RateLimiter.ofDefaults("foo");
    RateLimiterExports.ofIterable("boo_rate_limiter", singletonList(rateLimiter)).register(registry);
    final Supplier<Map<String, Double>> values = () -> HashSet.of("available_permissions", "waiting_threads").map(param -> Tuple.of(param, registry.getSampleValue("boo_rate_limiter", new String[] { "name", "param" }, new String[] { "foo", param }))).toMap(t -> t);
    // When
    final Map<String, Double> initialValues = values.get();
    // Then
    assertThat(initialValues).isEqualTo(HashMap.of("available_permissions", 50.0, "waiting_threads", 0.0));
}
Also used : Tuple(io.vavr.Tuple) CollectorRegistry(io.prometheus.client.CollectorRegistry) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) HashMap(io.vavr.collection.HashMap) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) InMemoryRateLimiterRegistry(io.github.resilience4j.ratelimiter.internal.InMemoryRateLimiterRegistry) Supplier(java.util.function.Supplier) Collections.singletonList(java.util.Collections.singletonList) Collections.singleton(java.util.Collections.singleton) HashSet(io.vavr.collection.HashSet) RateLimiterConfig(io.github.resilience4j.ratelimiter.RateLimiterConfig) RateLimiterRegistry(io.github.resilience4j.ratelimiter.RateLimiterRegistry) Map(io.vavr.collection.Map) CollectorRegistry(io.prometheus.client.CollectorRegistry) HashMap(io.vavr.collection.HashMap) Map(io.vavr.collection.Map) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) Test(org.junit.Test)

Example 14 with RateLimiter

use of io.github.resilience4j.ratelimiter.RateLimiter in project resilience4j by resilience4j.

the class RateLimiterMetrics method bindTo.

@Override
public void bindTo(MeterRegistry registry) {
    for (RateLimiter rateLimiter : rateLimiters) {
        final String name = rateLimiter.getName();
        Gauge.builder(getName(prefix, name, AVAILABLE_PERMISSIONS), rateLimiter, (cb) -> cb.getMetrics().getAvailablePermissions()).register(registry);
        Gauge.builder(getName(prefix, name, WAITING_THREADS), rateLimiter, (cb) -> cb.getMetrics().getNumberOfWaitingThreads()).register(registry);
    }
}
Also used : Gauge(io.micrometer.core.instrument.Gauge) MetricUtils.getName(io.github.resilience4j.micrometer.MetricUtils.getName) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) Objects.requireNonNull(java.util.Objects.requireNonNull) MeterBinder(io.micrometer.core.instrument.binder.MeterBinder) WAITING_THREADS(io.github.resilience4j.ratelimiter.utils.MetricNames.WAITING_THREADS) AVAILABLE_PERMISSIONS(io.github.resilience4j.ratelimiter.utils.MetricNames.AVAILABLE_PERMISSIONS) RateLimiterRegistry(io.github.resilience4j.ratelimiter.RateLimiterRegistry) DEFAULT_PREFIX(io.github.resilience4j.ratelimiter.utils.MetricNames.DEFAULT_PREFIX) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter)

Example 15 with RateLimiter

use of io.github.resilience4j.ratelimiter.RateLimiter in project resilience4j by resilience4j.

the class RateLimiterEventsEndpoint method getEventsStreamFilteredByRateLimiterNameAndEventType.

@RequestMapping(value = "stream/events/{rateLimiterName}/{eventType}", produces = MEDIA_TYPE_TEXT_EVENT_STREAM)
public SseEmitter getEventsStreamFilteredByRateLimiterNameAndEventType(@PathVariable("rateLimiterName") String rateLimiterName, @PathVariable("eventType") String eventType) {
    RateLimiterEvent.Type targetType = RateLimiterEvent.Type.valueOf(eventType.toUpperCase());
    RateLimiter rateLimiter = rateLimiterRegistry.getAllRateLimiters().find(rL -> rL.getName().equals(rateLimiterName)).getOrElseThrow(() -> new IllegalArgumentException(String.format("rate limiter with name %s not found", rateLimiterName)));
    Flux<RateLimiterEvent> eventStream = toFlux(rateLimiter.getEventPublisher()).filter(event -> event.getEventType() == targetType);
    return RateLimiterEventsEmitter.createSseEmitter(eventStream);
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RateLimiterEvent(io.github.resilience4j.ratelimiter.event.RateLimiterEvent) RateLimiterEventsEndpointResponse(io.github.resilience4j.ratelimiter.monitoring.model.RateLimiterEventsEndpointResponse) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) MediaType(org.springframework.http.MediaType) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Controller(org.springframework.stereotype.Controller) RateLimiterEventDTO(io.github.resilience4j.ratelimiter.monitoring.model.RateLimiterEventDTO) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) ReactorAdapter.toFlux(io.github.resilience4j.adapter.ReactorAdapter.toFlux) Flux(reactor.core.publisher.Flux) List(java.util.List) CircularEventConsumer(io.github.resilience4j.consumer.CircularEventConsumer) Seq(io.vavr.collection.Seq) Comparator(java.util.Comparator) EventConsumerRegistry(io.github.resilience4j.consumer.EventConsumerRegistry) RateLimiterRegistry(io.github.resilience4j.ratelimiter.RateLimiterRegistry) SseEmitter(org.springframework.web.servlet.mvc.method.annotation.SseEmitter) RateLimiterEvent(io.github.resilience4j.ratelimiter.event.RateLimiterEvent) RateLimiter(io.github.resilience4j.ratelimiter.RateLimiter) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RateLimiter (io.github.resilience4j.ratelimiter.RateLimiter)15 RateLimiterRegistry (io.github.resilience4j.ratelimiter.RateLimiterRegistry)9 Test (org.junit.Test)8 RateLimiterConfig (io.github.resilience4j.ratelimiter.RateLimiterConfig)5 CircularEventConsumer (io.github.resilience4j.consumer.CircularEventConsumer)2 EventConsumerRegistry (io.github.resilience4j.consumer.EventConsumerRegistry)2 RateLimiterEvent (io.github.resilience4j.ratelimiter.event.RateLimiterEvent)2 InMemoryRateLimiterRegistry (io.github.resilience4j.ratelimiter.internal.InMemoryRateLimiterRegistry)2 Seq (io.vavr.collection.Seq)2 Comparator (java.util.Comparator)2 List (java.util.List)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 ReactorAdapter.toFlux (io.github.resilience4j.adapter.ReactorAdapter.toFlux)1 RxJava2Adapter (io.github.resilience4j.adapter.RxJava2Adapter)1 MetricUtils.getName (io.github.resilience4j.micrometer.MetricUtils.getName)1 AtomicRateLimiter (io.github.resilience4j.ratelimiter.internal.AtomicRateLimiter)1 RateLimiterEventDTO (io.github.resilience4j.ratelimiter.monitoring.model.RateLimiterEventDTO)1 RateLimiterEventsEndpointResponse (io.github.resilience4j.ratelimiter.monitoring.model.RateLimiterEventsEndpointResponse)1 AVAILABLE_PERMISSIONS (io.github.resilience4j.ratelimiter.utils.MetricNames.AVAILABLE_PERMISSIONS)1 DEFAULT_PREFIX (io.github.resilience4j.ratelimiter.utils.MetricNames.DEFAULT_PREFIX)1