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>

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • MCP2515模块_mcp2515接收错误

    MCP2515模块_mcp2515接收错误1、在配置Linux编译选项时,开启相应的SPI选项,如下所示->DeviceDrivers->SPIsupportSPIsupport***SPIMasterControllerDrivers***-*-BitbangingSPImasterSamsungS3C24XXseriesSPI<>SamsungS3C24XXserie…

    2022年10月31日
  • undefined function or variable_function的使用

    undefined function or variable_function的使用今天用webpack打包项目,安装了less-loader模块之后报错,如下图:原因:less-loader安装的版本过高解决方案:1.npmuninstallless-loader2.npminstallless-loader@5.0.0

  • nginx 接口转发_nginx后端接口转发到内网

    nginx 接口转发_nginx后端接口转发到内网目前开发多数趋于前后端分离,后端开发人员有的时候懒得搭建前端环境,可是写后端又不便于联调,经常被这个困扰中,本文介绍如何用nginx转发。前提:有一套完整的环境,可以访问整个环境。环境地址,eghttp://wangzhi.com背景:开发人员不想搭建前端环境,可是又不便于联调。postman联调的话,参数拼接比较麻烦。步骤:1、本地项目启动,eg:localhost:80802、配置本地host127.0.0.1wangzhi.com说明:需要把环境地址,转到本地,

  • Java高并发程序设计学习笔记(九):锁的优化和注意事项

    Java高并发程序设计学习笔记(九):锁的优化和注意事项

  • LDR命令

    LDR命令  LDR指令用于从内存中将一个32位的字读取到指令中的目标寄存器中,如果目标寄存器为PC,则可以实现“长”跳转。主要有一下3种方式使用:ldrr0,_startldrr0,=_startldrpc,_start  逐条分析:一、ldrr0,_start  从内存地址_start的地方,把其对应的命令执行对应的“执行码”读入到r0中。二、ldrr0,=_start  …

  • string用法总结[建议收藏]

    要想使用标准C++中的string类,必须要包含#include<string>注意是<string>而不是<string.h>,带.h的是C语言中的头文件s

    2021年12月18日

发表回复

您的电子邮箱地址不会被公开。

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