Java高性能缓存框架之Caffeine详解

 更新时间:2023年12月29日 08:32:23   作者:_Romeo  
这篇文章主要介绍了Java高性能缓存框架之Caffeine详解,Caffeine是一个基于Java8的高性能缓存框架,号称趋于完美,Caffeine受启发于Guava Cache的API,使用API和Guava是一致的,需要的朋友可以参考下

Caffeine缓存框架

Caffeine是一个基于Java8的高性能缓存框架,号称趋于完美。

Caffeine受启发于Guava Cache的API,使用API和Guava是一致的。

它借鉴了Guava Cache和ConcurrentLinkedHashMap的设计经验。

在Springboot中使用Caffeine

在工程的pom文件引入caffeine的依赖,如下:

<dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.6.2</version>
        </dependency>

创建一个抽象类AbstractCaffineCache,该类使用范型来约束缓存的数据类型,并实现了三个方法,put、get、clear。

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/3/7 10:44
 */
public abstract class AbstractCaffeineCache<T> {
    protected LoadingCache<String, T> loadingCache;
    abstract LoadingCache<String, T> createLoadingCache();
    public boolean put(String key, T value) {
        if (loadingCache == null) {
            loadingCache = createLoadingCache();
        }
        loadingCache.put(key, value);
        return Boolean.TRUE;
    }
    public T get(String key) {
        if (loadingCache == null) {
            loadingCache = createLoadingCache();
        }
        try {
            return loadingCache.get(key);
        } catch (Exception e) {
            return null;
        }
    }
    public boolean clear(String key) {
        if (loadingCache == null) {
            loadingCache = createLoadingCache();
        }
        loadingCache.invalidate(key);
        return Boolean.TRUE;
    }
}

创建MyCaffeineCache的缓存类,该类缓存类。创建LoadingCache类,该类设置了缓存过期的时间,最大的缓存个数。

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/3/7 10:44
 */
public class MyCaffeineCache extends AbstractCaffeineCache {
    /**
     * Caffeine配置说明:
     * initialCapacity=[integer]: 初始的缓存空间大小
     * maximumSize=[long]: 缓存的最大条数
     * maximumWeight=[long]: 缓存的最大权重
     * expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期
     * expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期
     * refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
     * recordStats:开发统计功能
     *
     * @return
     */
    @Override
    LoadingCache createLoadingCache() {
        loadingCache = Caffeine.newBuilder()
                .expireAfterWrite(1000L, TimeUnit.MILLISECONDS)
                .initialCapacity(10)
                .maximumSize(100)
                .recordStats()
                .build((CacheLoader<String, String>) key -> null);
        return loadingCache;
    }
}

将MyCaffeineCache注入到spring ioc中,代码如下:

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/3/7 10:45
 */
@Configuration
public class CaffeineCacheConfig {
    @Bean
    public MyCaffeineCache MyCaffeineCache(){
        return new MyCaffeineCache();
    }
}

如何使用。

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/1/6 9:45
 */
@Aspect
@Component
@Slf4j
public class IdempotentAspect extends BaseController {
    @Resource
    private MyCaffeineCache cache;
    private static final ThreadLocalUtil threadLocalUtil = new ThreadLocalUtil();
    @Around(value = "@annotation(idempotent)")
    public Object around(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {
        UserBO user = getUserBO(request);
        Integer userId = user.getUserId();
        String userRequest = userId + request.getRequestURI();
        threadLocalUtil.setLocalUserRequest(userRequest);
        Object uuid = cache.get(userRequest);
        VerifyUtils.throwWhen(uuid != null, idempotent.value());
        return joinPoint.proceed();
    }
    @AfterReturning(value = "@annotation(idempotent)")
    public void afterReturning(JoinPoint point, Idempotent idempotent) {
        try {
            cache.put(threadLocalUtil.getLocalUserRequest(), UUIDUtil.simpleUUID());
        } finally {
            threadLocalUtil.clearLocalUserRequest();
        }
    }
}

使用本地缓存可以加快页面响应速度,缓存分布式缓存读压力,大量、高并发请求的网站比较适用

Caffeine配置说明:

  • initialCapacity=[integer]: 初始的缓存空间大小
  • maximumSize=[long]: 缓存的最大条数
  • maximumWeight=[long]: 缓存的最大权重
  • expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期
  • expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期
  • refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
  • recordStats:开发统计功能

注意: expireAfterWrite和expireAfterAccess同时存在时,以expireAfterWrite为准。

到此这篇关于Java高性能缓存框架之Caffeine详解的文章就介绍到这了,更多相关缓存框架Caffeine内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot项目集成Flyway详细过程

    SpringBoot项目集成Flyway详细过程

    今天带大家学习SpringBoot项目集成Flyway详细过程,文中有非常详细的介绍及代码示例,对正在学习java的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05
  • springboot中实现通过后台创建临时表

    springboot中实现通过后台创建临时表

    这篇文章主要介绍了springboot中实现通过后台创建临时表操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 深入理解Java 类加载全过程

    深入理解Java 类加载全过程

    这篇文章主要介绍了深入理解Java 类加载全过程的相关资料,需要的朋友可以参考下
    2017-02-02
  • SpringBoot快速实现接口消息加密的过程详解

    SpringBoot快速实现接口消息加密的过程详解

    在项目中,为了保证数据的安全,我们常常会对传递的数据进行加密,常用的加密算法包括对称加密(AES)和非对称加密(RSA),博主选取码云上最简单的API加密项目进行下面的讲解,需要的朋友可以参考下
    2023-11-11
  • 深入理解Java虚拟机 JVM 内存结构

    深入理解Java虚拟机 JVM 内存结构

    本节将会介绍一下JVM的内存结构,JVM运行时数据区的各个组成部分:堆,方法区,程序计数器,Java虚拟机栈,本地方法栈,还会对Java堆的分代划分做个简单的介绍
    2021-09-09
  • java中的SpringBoot框架

    java中的SpringBoot框架

    这篇文章主要介绍了java学习之SpringBoot框架,文章基于Java的相关资料展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-04-04
  • SpringCloud服务网关Gateway的使用教程详解

    SpringCloud服务网关Gateway的使用教程详解

    SpringCloud Gateway是Spring体系内的一个全新项目,它旨在为微服务架构提供一种简单有效的统一的API路由管理方式。本文就来为大家详细讲讲Gateway的使用教程,需要的可以参考一下
    2022-09-09
  • RocketMQ实现消息分发的步骤

    RocketMQ实现消息分发的步骤

    RocketMQ 实现消息分发的核心机制是通过 Topic、Queue 和 Consumer Group 的配合实现的,下面给大家介绍RocketMQ实现消息分发的步骤,感兴趣的朋友一起看看吧
    2024-03-03
  • Spring Boot中slf4j日志依赖关系示例详解

    Spring Boot中slf4j日志依赖关系示例详解

    在项目开发中,记录日志是必做的一件事情。而当我们使用Springboot框架时,记录日志就变得极其简单了。下面这篇文章主要给大家介绍了关于Spring Boot中slf4j日志依赖关系的相关资料,需要的朋友可以参考下
    2018-11-11
  • Java中递归原理实例分析

    Java中递归原理实例分析

    这篇文章主要介绍了Java中递归原理,实例分析了java中递归的原理与实现方法,以及使用过程中的相关技巧,需要的朋友可以参考下
    2015-05-05

最新评论