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


相关推荐

  • hashmap面试题简书_elasticsearch面试常问问题

    hashmap面试题简书_elasticsearch面试常问问题BAT面试必问HashMap源码分析

    2022年4月22日
    52
  • 阿里云ddns过程记录

    阿里云ddns过程记录申请了阿里云一年的动态域名,收费的,闲置了几个月,用openwrt一直没成功,最近研究asterisk部署,有个公网的ddns还是方便不少,所以把闲置的域名得拾起来了,过程如下1.开启阿里云后台权限(在访问控制菜单中,文章最后有链接)AliyunDNSReadOnlyAccessAliyunDNSFullAccess2.下载脚本运行GitHub-risfeng/aliyun-ddns-shell:阿里云域名解析动态更新IPShell脚本阿里云域名解析动态更新IPSh

    2022年6月6日
    30
  • laravel 验证码手机与提交手机的验证?

    laravel 验证码手机与提交手机的验证?

    2021年10月25日
    43
  • 我的世界服务器怎么开启坐标显示,我的世界怎么设置坐标-坐标设置攻略「建议收藏」

    我的世界服务器怎么开启坐标显示,我的世界怎么设置坐标-坐标设置攻略「建议收藏」在我的世界中,每个玩家都有过迷路,找不到家的经历,或者是找到了资源,准备下次来采集的时候又找不到了,这时候坐标就很重要了,那么我的世界怎么设置坐标呢?跟小编一起来看看我的世界坐标设置攻略吧!我的世界坐标设置攻略在我的世界中想要设置坐标一般是指设置坐标传送点,以便快速传送。首先需要打开坐标的设置,可以在页面设置中把“显示坐标”打开,之后确认自己要传送的地点坐标,之后输入命令行/tp,如tp0…

    2022年9月23日
    1
  • java中级面试题及答案_Java中级面试题

    java中级面试题及答案_Java中级面试题一、Java笔试题基础1.Java中的异常有哪几类?分别怎么使用?检出异常,非检出异常。检出异常需要try…catch才能编译通过。非检出异常不用try…catch也能编译通过。RuntimeException是非检出异常,不需要try…catch也能编译通过。IoException,SQLException等等其他所有异常都是检出异常,必须要try…catach才能编译通过。2.常用的集合类有哪些?比如List如何排序?分两种,一种实现Set接口,一种是实现List接口的。Set:Tre

    2022年10月12日
    2
  • Centos7 下载安装配置Jenkins教程

    Centos7 下载安装配置Jenkins教程这篇博文总结下如何下载安装和配置Jenkins

    2022年5月14日
    34

发表回复

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

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