All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.dengchen2020.ratelimiter.redis.RedisRateLimiterAutoConfiguration Maven / Gradle / Ivy

There is a newer version: 0.0.28
Show newest version
package io.github.dengchen2020.ratelimiter.redis;

import io.github.dengchen2020.ratelimiter.RateLimiterInterceptor;
import io.github.dengchen2020.ratelimiter.properties.RateLimiterBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.Duration;

/**
 * Redis分布式限流自动配置
 * @author dengchen
 * @since 2024/8/3
 */
@ConditionalOnClass(LettuceConnectionFactory.class)
@ConditionalOnProperty(value = "dc.ratelimiter.type", havingValue = "redis")
@EnableConfigurationProperties(RateLimiterBuilder.class)
@Configuration(proxyBeanMethods = false)
public class RedisRateLimiterAutoConfiguration {

    @ConditionalOnProperty(value = "dc.ratelimiter.enabled", matchIfMissing = true, havingValue = "true")
    @Configuration(proxyBeanMethods = false)
    static class DistributedRateLimiterInterceptorRegister implements WebMvcConfigurer {

        private final StringRedisTemplate redisTemplate;

        DistributedRateLimiterInterceptorRegister(StringRedisTemplate stringRedisTemplate) {
            this.redisTemplate = stringRedisTemplate;
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new RateLimiterInterceptor(new RedisRateLimiter(Duration.ofSeconds(1), redisTemplate), new RedisRateLimiter(Duration.ofMinutes(1), redisTemplate)));
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy