Created
April 4, 2025 06:53
-
-
Save hu553in/f68affba85a8a2f219852f1af3080b72 to your computer and use it in GitHub Desktop.
Caffeine cache for Prometheus tagged counters in Spring Boot app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.github.benmanes.caffeine.cache.Caffeine; | |
import com.github.benmanes.caffeine.cache.LoadingCache; | |
import io.micrometer.core.instrument.Counter; | |
import io.micrometer.core.instrument.MeterRegistry; | |
import io.micrometer.core.instrument.Tag; | |
import io.micrometer.core.instrument.binder.cache.CaffeineCacheMetrics; | |
import java.time.Duration; | |
import org.springframework.stereotype.Component; | |
import static java.util.Arrays.asList; | |
@Component | |
public class Counters { | |
private final LoadingCache<Key, Counter> counters; | |
public Counters(MeterRegistry meterRegistry) { | |
counters = Caffeine.newBuilder() | |
.expireAfterWrite(Duration.ofMinutes(5)) | |
.recordStats() | |
.build(key -> Counter | |
.builder(key.counterName) | |
.tag("account_id", String.valueOf(key.accountId)) | |
.tags(asList(key.additionalTags)) | |
.register(meterRegistry)); | |
CaffeineCacheMetrics.monitor(meterRegistry, counters, "counters_cache"); | |
} | |
public void increment(Integer accountId, String counterName, Tag... additionalTags) { | |
counters.get(new Key(accountId, counterName, additionalTags)).increment(); | |
} | |
private record Key(Integer accountId, String counterName, Tag... additionalTags) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment