com.founder.core.starter.RateLimiterAutoConfiguration Maven / Gradle / Ivy
package com.founder.core.starter;
import com.founder.core.ratelimiter.RateLimitAspectHandler;
import com.founder.core.ratelimiter.RateLimiterService;
import com.founder.core.ratelimiter.RuleProvider;
import com.founder.core.starter.properties.RateLimiterProperties;
import com.founder.core.starter.properties.RateLimiterRedisProperties;
import com.founder.core.web.RateLimitExceptionHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//https://gitee.com/kailing/ratelimiter-spring-boot-starter
@Configuration
@ConditionalOnProperty(prefix = RateLimiterProperties.PREFIX, name = "enabled", havingValue = "true")
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableConfigurationProperties({RateLimiterProperties.class, RateLimiterRedisProperties.class})
@Import({RateLimitAspectHandler.class, RateLimitExceptionHandler.class})
public class RateLimiterAutoConfiguration {
private final RateLimiterProperties limiterProperties;
private final RateLimiterRedisProperties limiterRedisProperties;
public final static String REDISSON_BEAN_NAME = "rateLimiterRedissonBeanName";
public RateLimiterAutoConfiguration(RateLimiterProperties limiterProperties,RateLimiterRedisProperties limiterRedisProperties) {
this.limiterProperties = limiterProperties;
this.limiterRedisProperties = limiterRedisProperties;
}
@Bean(name = REDISSON_BEAN_NAME, destroyMethod = "shutdown")
RedissonClient redisson() {
Config config = new Config();
if (limiterProperties.getRedisClusterServer() != null) {
config.useClusterServers().setPassword(limiterRedisProperties.getPassword())
.addNodeAddress(limiterProperties.getRedisClusterServer().getNodeAddresses());
} else {
config.useSingleServer().setAddress("redis://"+limiterRedisProperties.getHost()+":"+limiterRedisProperties.getPort())
.setDatabase(limiterRedisProperties.getDatabase())
.setPassword(limiterRedisProperties.getPassword());
}
config.setEventLoopGroup(new NioEventLoopGroup());
return Redisson.create(config);
}
@Bean
public RuleProvider bizKeyProvider() {
return new RuleProvider();
}
@Bean
public RateLimiterService rateLimiterInfoProvider() {
return new RateLimiterService(redisson());
}
}