org.zodiac.autoconfigure.redis.RedisRateLimiterAutoConfiguration Maven / Gradle / Ivy
package org.zodiac.autoconfigure.redis;
import java.util.List;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.zodiac.autoconfigure.redis.condition.ConditionalOnRedisEnabled;
import org.zodiac.commons.constants.SystemPropertiesConstants;
import org.zodiac.redis.ratelimiter.RedisRateLimiterAspect;
import org.zodiac.redis.ratelimiter.RedisRateLimiterClient;
@SpringBootConfiguration
@ConditionalOnRedisEnabled
@ConditionalOnProperty(value = SystemPropertiesConstants.Zodiac.SPRING_REDIS_RATE_LIMITER_ENABLED, havingValue = "true")
public class RedisRateLimiterAutoConfiguration {
private final ApplicationContext applicationContext;
private final RedisCacheCloudProperties redisCacheCloudProperties;
public RedisRateLimiterAutoConfiguration(ApplicationContext applicationContext, RedisCacheCloudProperties redisCacheCloudProperties) {
this.applicationContext = applicationContext;
this.redisCacheCloudProperties = redisCacheCloudProperties;
}
@Bean
@ConditionalOnMissingBean
protected RedisRateLimiterClient redisRateLimiter(StringRedisTemplate redisTemplate, Environment environment) {
RedisScript> redisRateLimiterScript = redisRateLimiterScript();
return new RedisRateLimiterClient(redisTemplate, redisRateLimiterScript, environment);
}
@Bean
@ConditionalOnMissingBean
protected RedisRateLimiterAspect redisRateLimiterAspect(RedisRateLimiterClient rateLimiterClient) {
return new RedisRateLimiterAspect(rateLimiterClient, applicationContext);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private RedisScript> redisRateLimiterScript() {
DefaultRedisScript redisScript = new DefaultRedisScript<>();
Resource scriptLocation = redisCacheCloudProperties.getRateLimiter().getScriptLocation();
redisScript.setLocation(null != scriptLocation ? scriptLocation : new ClassPathResource("META-INF/redis/scripts/platform_rate_limiter.lua"));
redisScript.setResultType(List.class);
return redisScript;
}
}