1、缓存(Cache)-工具类

  1. 1、需引入插件依赖
  2. <dependency>
  3. <groupId>com.google.guava</groupId>
  4. <artifactId>guava</artifactId>
  5. <version>16.0.1</version>
  6. </dependency>
  7. 2Demo
  8. @Slf4j
  9. public class CacheUtil {
  10. public static CacheUtil create() {
  11. return new CacheUtil();
  12. }
  13. public static CacheUtil create(Long number, TimeUnit timeUnit) {
  14. return new CacheUtil(number, timeUnit);
  15. }
  16. private Cache<String, Object> customCache;
  17. /**
  18. * 无参构造:缓存过期时间(指定对象被写入到缓存后多久过期),默认为1天.
  19. * .recordStats(): 开启统计信息开关,统计缓存的命中率
  20. */
  21. private CacheUtil() {
  22. customCache = CacheBuilder.newBuilder()
  23. .expireAfterWrite(1L, TimeUnit.HOURS)
  24. .recordStats()
  25. .removalListener(new RemovalListener<Object, Object>() {
  26. @Override
  27. public void onRemoval(RemovalNotification<Object, Object> notification) {
  28. log.info(notification.getKey() + " was removed, cause is " + notification.getCause());
  29. }
  30. })
  31. .build();
  32. cleanCache();
  33. }
  34. /**
  35. * 缓存过期时间(指定对象被写入到缓存后多久过期),为传入的单位
  36. * .recordStats(): 开启统计信息开关,统计缓存的命中率
  37. * @param timeUnit: 过期时间单位,秒分时日
  38. */
  39. private CacheUtil(Long number, TimeUnit timeUnit) {
  40. //如果传入过期时间数值为空,则默认为1
  41. if(number == null){
  42. number = 1L;
  43. }
  44. customCache = CacheBuilder.newBuilder()
  45. .expireAfterWrite(number, timeUnit)
  46. .recordStats()
  47. .removalListener(new RemovalListener<Object, Object>() {
  48. @Override
  49. public void onRemoval(RemovalNotification<Object, Object> notification) {
  50. log.info(notification.getKey() + " was removed, cause is " + notification.getCause());
  51. }
  52. })
  53. .build();
  54. cleanCache();
  55. }
  56. /**
  57. * 清空缓存
  58. */
  59. public void cleanCache() {
  60. customCache.cleanUp();
  61. }
  62. public Object get(String key, Callable<Object> callable) throws ExecutionException {
  63. return customCache.get(key, callable);
  64. }
  65. public Object get(String key) throws ExecutionException {
  66. return customCache.getIfPresent(key);
  67. }
  68. public void put(String key, Object value) throws ExecutionException {
  69. customCache.put(key, value);
  70. }
  71. public static void main(String[] args) throws ExecutionException {
  72. CacheUtil cacheUtil = CacheUtil.create();
  73. cacheUtil.put("test",1111);
  74. Object test = cacheUtil.get("test");
  75. System.out.println(test.toString());
  76. cacheUtil.cleanCache();
  77. System.out.println(cacheUtil.get("test"));
  78. }
  79. }