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


相关推荐

  • OCL功率放大电路[通俗易懂]

    OCL功率放大电路[通俗易懂]OCL(OutputCapacitorLess)是OTL电路的升级,指省去输出端大电容的功率放大电路,省去了输出电容,使系统的低频响应更加平滑。缺点是必须用双电源供电,增加了电源的复杂性。1.工作原理当输入信号为正半周期时,V1导通,V2截止,电流方向为+vcc,V1的集电极,V1的发射极,负载,地。当输入信号为负半周期时,V1截止,V2导通,电流方向为地,负载,V2的发射极,V2的集…

    2022年6月5日
    58
  • 基于USB数据采集卡(DAQ)与IO模块的热电阻温度采集「建议收藏」

    思迈科华针对热电阻温度传感器温度采集的方案热电阻简介这里主要介绍一下铂热电阻,Pt100是铂热电阻,它的阻值跟温度的变化成正比。PT100的阻值与温度变化关系为:当PT100温度为0℃时它的阻值为100欧姆,在100℃时它的阻值约为138.5欧姆。它的工业原理:当PT100在0摄氏度的时候,它的阻值为100欧姆,它的阻值会随着温度上升而成匀速增长。国标热电阻主要接线方式有三种:二线制:在热电阻的两端各连接一根导线来引出电阻信号的方式叫二线制:这种引线方法很简单,但由于连接导线必然存在引线电阻R,电阻

    2022年4月7日
    52
  • 用python 打印九九乘法表的7种方式 (python经典编程案例)[通俗易懂]

    用python 打印九九乘法表的7种方式 (python经典编程案例)[通俗易懂]用python打印九九乘法表,代码如下:#九九乘法表foriinrange(1,10):forjinrange(1,i+1):print(‘{}x{}={}\t’.format(j,i,i*j),end=”)print()执行结果如下图:…

    2022年6月29日
    43
  • JAVAdebug_java如何设置断点

    JAVAdebug_java如何设置断点大家好,我是时间财富网智能客服时间君,上述问题将由我为大家进行解答。以eclipse为例,debug的用法:1、首先在一个java文件中设断点,然后debugas,opendebugDialog,然后在对话框中选类后,Run。2、F5键与F6键均为单步调试,F5是stepinto,也就是进入本行代码中执行,F6是stepover,也就是执行本行代码,跳到下一行。3、F7是跳出函数,F8是…

    2022年10月15日
    0
  • MongoDb的ConnectionString链接字符串解析

    MongoDb的ConnectionString链接字符串解析MongoDb的ConnectionString链接字符串解析,如下图所示。

    2022年7月12日
    57
  • File类createNewFile与createTempFile的区别[通俗易懂]

    自:http://www.cnblogs.com/huangyibo/p/3667714.html最近,在看代码时看到了一个方法,File.createTempFile(),由此联想到File.createNewFile()方法,一时间不知道两者到底有什么区别,感觉都是创建新文件嘛,后来查看api文档介绍,并经过自己动手试验,终于有了一个较为清楚地认识。 1.File的crea…

    2022年4月11日
    39

发表回复

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

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