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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java解析XML的所需Jar包「建议收藏」

    java解析XML的所需Jar包「建议收藏」链接:https://pan.baidu.com/s/1ck6YIRT2MpiDLsCAxi-I9Q提取码:yjss其中包括dom4j和jaxen包

    2022年5月9日
    179
  • 检查网站有没有被挂马_网站在线挂马检测工具

    检查网站有没有被挂马_网站在线挂马检测工具首先,我们来看看网站被挂马的危害性。网站被挂马后,一方面是系统资源,流量带宽资源的巨大损失,另一方面也成为了传播网页木马的“傀儡帮凶”,严重影响到网站的公众信誉度。很多网页木马都是利益驱动,偷盗各类帐号密码,如电子银行帐户和密码、游戏帐号和密码、邮箱帐户和密码、qq/MSN帐号和密码等;另外,使得客户端被安装恶意插件,强迫浏览黑客指定的网站,或者被利用攻击某个站点等。  我们知道了网站被挂马

    2022年9月27日
    3
  • L1正则化的理解(l1和l2正则化代表什么意思)

    在论文中看到L1正则化,可以实现降维,加大稀疏程度,菜鸟不太懂来直观理解学习一下。在工程优化中也学习过惩罚函数这部分的内容,具体给忘记了。而正则化正是在损失函数后面加一个额外的惩罚项,一般就是L1正则化和L2正则化。之所以叫惩罚项就是为了对损失函数(也就是工程优化里面的目标函数)的某个或些参数进行限制,从而减少计算量。L1正则化的损失函数是是不光滑的,L2正则化的损失函数…

    2022年4月16日
    61
  • 网页中嵌入特殊字体

    网页中嵌入特殊字体

    2021年5月26日
    104
  • 判断IPV6地址格式是否正确

    判断IPV6地址格式是否正确1 判断 IPV6 格式字串是否正确此功能代码实现判断 IPV6 地址是否正确 正确返回 1 错误误返回 0 defineH x unsignedchar amp x 0 defineL x unsignedchar amp x 1 char abbr ipv6 字符串 unsignedchar ret buf

    2025年8月21日
    1
  • 树莓派是什么 树莓派能做什么 树莓派的功能用途

    树莓派是什么 树莓派能做什么 树莓派的功能用途阿里云官方镜像源:https://developer.aliyun.com/mirror/?utm_content=g_1000304579树莓派是指RaspberryPi,是为学习计算机编程教育而设计,只有信用卡大小的微型电脑,其系统基于Linux。随着Windows10IoT的发布,我们也将可以用上运行Windows的树莓派。下面小编给大家介绍一下“树莓派是什么树莓派能做什么树莓派的功能用途”1.树莓派是什么树莓派是指RaspberryPi,是为学习计算机编程

    2022年6月10日
    38

发表回复

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

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