MarcGiffing / bucket4j-spring-boot-starter

Spring Boot Starter for Bucket4j
Apache License 2.0
298 stars 63 forks source link

Adding a cache key prefix option #328

Open phombal opened 2 weeks ago

phombal commented 2 weeks ago

Hi! I am working with a cache where it is required for a prefix to be added to the cache key before keying into the cache. However, when I begin the cache key with this prefix, it seems like there is a url that is being prepended to the entirety of the cache key, which prevents the entry from keying into the cache. This feature seems to be implemented here: https://github.com/MarcGiffing/bucket4j-spring-boot-starter/issues/19. I was wondering whether there is any way that we can add functionality for a prefix to prepend the entirety of the key (url + specified key) or restructure the key as a whole to be able to add a prefix. Thank you!

MarcGiffing commented 2 weeks ago

I haven't tried it but maybe you can try something like this:

@Service
@Primary
public class CustomRateLimitService extends RateLimitService {

    private final ExpressionService expressionService;

    public CustomRateLimitService(ExpressionService expressionService) {
        super(expressionService);
        this.expressionService = expressionService;
    }

    @Override
    public <R> KeyFilter<R> getKeyFilter(String url, RateLimit rateLimit) {
        return expressionParams -> {
            return expressionService.parseString(rateLimit.getCacheKey(), expressionParams);
        };
    }
}