SpringBoot2 缓存之王caffeine

怼烎@ 2022-10-15 10:46 252阅读 0赞
  1. <dependency>
  2. <groupId>com.github.ben-manes.caffeine</groupId>
  3. <artifactId>caffeine</artifactId>
  4. <version>2.9.0</version>
  5. </dependency>

顺便写了个工具类配合SpringBoot使用:

  1. package com.ciih.refineinner.cache;
  2. import com.github.benmanes.caffeine.cache.Cache;
  3. import com.github.benmanes.caffeine.cache.Caffeine;
  4. import org.springframework.stereotype.Component;
  5. import java.util.concurrent.TimeUnit;
  6. import java.util.function.Function;
  7. /**
  8. * 缓存之王
  9. *
  10. * @author Lenovo
  11. */
  12. @Component
  13. public class CaffeineService {
  14. private Cache<String, String> cache;
  15. public CaffeineService() {
  16. this.cache = Caffeine.newBuilder()
  17. .expireAfterWrite(15, TimeUnit.MINUTES)
  18. .maximumSize(100)
  19. .build();
  20. }
  21. /**
  22. * 存储K-V
  23. *
  24. * @param key
  25. * @param value
  26. * @return
  27. */
  28. public String put(String key, String value) {
  29. cache.put(key, value);
  30. return key;
  31. }
  32. /**
  33. * 获取K-V
  34. *
  35. * @param key
  36. * @return
  37. */
  38. public String getIfPresent(String key) {
  39. return cache.getIfPresent(key);
  40. }
  41. public String get(String key, Function<String, String> function) {
  42. return cache.get(key, function);
  43. }
  44. public void remove(String key) {
  45. cache.invalidate(key);
  46. }
  47. }

发表评论

表情:
评论列表 (有 0 条评论,252人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Caffeine缓存

    简介 我们来看看 [Caffeine][] — 一个高性能的 Java 缓存库。 缓存和 Map 之间的根本区别在于缓存可以回收存储的 item。 回收策略为在指定时