mybatisplus使用Caffeine作为mapper层二级缓存

mybatisplus使用Caffeine作为mapper层二级缓存引入Caffeine<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>2.9.0</version></dependency>封装好的工具类:pack

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

引入Caffeine

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

封装好的工具类:

package com.ciih.authcenter.client.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 缓存之王
 *
 * @author Lenovo
 */
@Component
public class CaffeineService {

    private Cache<Object, Object> cache;

    public CaffeineService() {
        this.cache = Caffeine.newBuilder()
                //过期策略:一分钟没有读取,则过期删除
                .expireAfterWrite(1, TimeUnit.MINUTES)
                //允许容量100个,超过自动删除
                .maximumSize(100)
                .build();
    }

    /**
     * 存储K-V
     *
     * @param key
     * @param value
     * @return
     */
    public Object put(Object key, Object value) {
        cache.put(key, value);
        return key;
    }

    /**
     * 获取K-V
     *
     * @param key
     * @return
     */
    public Object getIfPresent(Object key) {
        return cache.getIfPresent(key);
    }

    public Object get(Object key, Function<Object, Object> function) {
        return cache.get(key, function);
    }

    public void remove(Object key) {
        cache.invalidate(key);
    }

    public void cleanUp() {
        cache.cleanUp();
    }

    public long estimatedSize() {
        return cache.estimatedSize();
    }
}

Mybatis缓存实现类



import cn.hutool.extra.spring.SpringUtil;
import com.ciih.authcenter.client.util.CaffeineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 二级缓存实现
 *
 * @author Lenovo
 */
@Slf4j
public class MybatisCache implements Cache {

    private CaffeineService caffeineService;

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    private String id;

    public MybatisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }


    @Override
    public void putObject(Object key, Object value) {
        if (caffeineService == null) {
            caffeineService = SpringUtil.getBean(CaffeineService.class);
        }
        if (value != null) {
            caffeineService.put(key, value);
        }
    }

    @Override
    public Object getObject(Object key) {
        if (caffeineService == null) {
            caffeineService = SpringUtil.getBean(CaffeineService.class);
        }
        try {
            if (key != null) {
                return caffeineService.getIfPresent(key);
            }
        } catch (Exception e) {
            log.error("缓存出错 ");
        }
        return null;
    }

    /**
     * As of 3.3.0 this method is only called during a rollback
     * for any previous value that was missing in the cache.
     * This lets any blocking cache to release the lock that
     * may have previously put on the key.
     * A blocking cache puts a lock when a value is null
     * and releases it when the value is back again.
     * This way other threads will wait for the value to be
     * available instead of hitting the database.
     *
     * @param key The key
     * @return Not used
     */
    @Override
    public Object removeObject(Object key) {
        if (caffeineService == null) {
            caffeineService = SpringUtil.getBean(CaffeineService.class);
        }
        caffeineService.remove(key);
        return null;
    }

    /**
     * Clears this cache instance.
     */
    @Override
    public void clear() {
        if (caffeineService == null) {
            caffeineService = SpringUtil.getBean(CaffeineService.class);
        }
        caffeineService.cleanUp();
    }

    /**
     * Optional. This method is not called by the core.
     *
     * @return The number of elements stored in the cache (not its capacity).
     */
    @Override
    public int getSize() {
        if (caffeineService == null) {
            caffeineService = SpringUtil.getBean(CaffeineService.class);
        }
        return (int) caffeineService.estimatedSize();
    }

    /**
     * Optional. As of 3.2.6 this method is no longer called by the core.
     * <p>
     * Any locking needed by the cache must be provided internally by the cache provider.
     *
     * @return A ReadWriteLock
     */
    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}

配置一下Dao接口

@CacheNamespace(implementation= MybatisCache.class,eviction=MybatisCache.class)
public interface SchoolDao extends EasyBaseMapper<School> {
    
}

配置xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ciih.authcenter.client.dao.SchoolDao">
    <cache-ref namespace="com.ciih.authcenter.client.dao.SchoolDao"/>

</mapper>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/188890.html原文链接:https://javaforall.net

(0)
上一篇 2026年4月15日 上午11:25
下一篇 2026年4月15日 上午11:31


相关推荐

  • WSAStartup与WSACleanup

    WSAStartup与WSACleanup文章来源无法查清 转载只是为了日后方便 WSAStartup 与 WSACleanupWS 应该与 WSACleanup 成对使用 WSAStartup 的功能是初始化 WinsockDLL WSACleanup 是来解除与 Socket 库的绑定并且释放 Socket 库所占用的系统资源 在 Windows 下 Socket 是以 DLL 的形式实现的 在 DLL 内部维持着一个计数器 只有第一次

    2026年3月19日
    2
  • suricata匹配从入门到精通(三)—-开始编写简单的snort规则

    suricata匹配从入门到精通(三)—-开始编写简单的snort规则suricata 兼容 snort 规则的大部分语法 今天我来教大家编写一条检测请求的规则 基于 suricata6 0 x 版本 欢迎关注专栏 会持续更新

    2026年3月17日
    1
  • matlab条件跳出语句,if语句跳出循环

    matlab条件跳出语句,if语句跳出循环break跳出的是if语句,还是for循环break跳出的是for循环。break在一些计算机编程语言中是保留字,其作用大多情况下是终止所在层的循环。1、break语句对if-else的条件语句不起作用。2、在多层循环中,一个break语句只向外跳一层。在C语言的switch(开关语句)中,break语句还可用来在执行完一个case(分支)后立即跳出当前switch结构。扩展资料:…

    2022年6月4日
    66
  • 项目经理的职业化素养建设——石化干部管理学院培训「建议收藏」

    项目经理的职业化素养建设——石化干部管理学院培训「建议收藏」5月26日,应邀到中石化干部培训管理学院,给中石化海外新项目经理进行《项目经理职业化素养和核心能力建设》的培训。中石化干部培训管理学院坐落在北京立水桥畔,是中石化培训和培养干部的基地。参训的学员主要为中石化的海外项目经理,学员年龄在30-40岁之间,长期在海外工作,主管中石化海外项目管理,具有很强项目管理实践经验。本次培训定位在讲授“作为一个项目经理应该培养和建设什么样的职业化素养和和核心能力”,

    2022年10月16日
    5
  • magic_quote

    magic_quote

    2021年8月17日
    82
  • 对cms的一些感想英文_CMS概念

    对cms的一些感想英文_CMS概念在很久以前开个网站基本上只有技术人员才可以实现的,曾几何时出现的cms系统,使架设网站的技术门槛大大的降低,只要有个空间,有个域名,会打字就可以开网站,后来又出来了web2.0,blog。但是毕竟这些都是一些商业炒作。记得当初最先使用的网站管理系统使动易,当时的动易因为盗版的问题采用动易组件,虽然网站制作很容易但是因为动易组件的问题造成服务…

    2022年10月19日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号