当前位置: 代码网 > it编程>编程语言>Java > 浅析SpringBoot整合Mybatis如何实现二级缓存

浅析SpringBoot整合Mybatis如何实现二级缓存

2025年05月15日 Java 我要评论
mybatis 原生二级缓存,是指多个sqlsession之间共享数据,但是也可以使用redis这样的缓存作为存储点。 但是不支持mybatisplus 里的方法。处理类,用于拦截mapper缓存。i

mybatis 原生

二级缓存,是指多个sqlsession之间共享数据,但是也可以使用redis这样的缓存作为存储点。 但是不支持mybatisplus 里的方法。

处理类,用于拦截mapper缓存。

import org.apache.ibatis.cache.cache;
public record mybatisrediscache(string id) implements cache {

    private static final stringredistemplate redistemplate;

    static {
        redistemplate = springutil.getbean(stringredistemplate.class);
    }

    @override
    public string getid() {
        return id;
    }

    @override
    public void putobject(object key, object value) {
        if (value != null) {
            redistemplate.opsforvalue().set(getkey(key), jsonutil.tojsonstr(value));
        }
    }

    @override
    public object getobject(object key) {
        string string = redistemplate.opsforvalue().get(getkey(key));
        if (string == null) return null;
        return isarray(string);
    }

    @override
    public object removeobject(object key) {
        string rediskey = getkey(key);
        object value = redistemplate.opsforvalue().get(rediskey);
        redistemplate.delete(rediskey);
        return value;
    }

    @override
    public void clear() {
        redistemplate.delete(objects.requirenonnull(redistemplate.keys(getkey("*"))));
    }

    @override
    public int getsize() {
        return 0;
    }

    private string getkey(object key) {
        return id + ":" + key.hashcode();
    }

    public object isarray(string str) {
        json json = jsonutil.parse(str);
        if (json instanceof cn.hutool.json.jsonarray) {
            // 是数组
            return jsonutil.tolist((cn.hutool.json.jsonarray) json, object.class);
        }
        if (json instanceof cn.hutool.json.jsonobject) {
            // 是对象
            return jsonutil.tobean((cn.hutool.json.jsonobject) json, object.class);
        }
        throw new runtimeexception("缓存数据格式错误");
    }

}

mapper xml

一定要加 cache-ref 才能进行二级缓存

<mapper namespace="com.example.dao.usermapper">

    <cache-ref namespace="com.example.dao.usermapper"/>

    <select id="selectall" resulttype="com.example.demo">
        select *
        from demo
    </select>
</mapper>

配置 cachenamespace 使用就可以了

@cachenamespace(implementation = mybatisrediscache.class)
public interface usermapper extends basemapper<demo> {

    list<demo> selectall();

}

spring cache

@configuration
@enablecaching
public class rediscacheconfig {

    @bean
    public cachemanager cachemanager(redisconnectionfactory factory) {
        rediscacheconfiguration config = rediscacheconfiguration.defaultcacheconfig()
                .entryttl(duration.ofminutes(10)) // 默认缓存 10 分钟
                .disablecachingnullvalues() // 避免存入控制
                .serializevalueswith( // 设置序列化
                        redisserializationcontext.serializationpair.fromserializer(new genericjackson2jsonredisserializer())
                );
        // 返回
        return rediscachemanager.builder(factory).cachedefaults(config).build();
    }

}

cacheable 缓存、cacheevict 删除,拼接 key

@service
public class demoservice extends serviceimpl<usermapper, demo> {

    @cacheable(value = "user:cache", key = "#id")
    public demo getone(long id) {
        return getbyid(id);
    }


    @caching(evict = {
            @cacheevict(value = "user:cache", key = "#id"),
            @cacheevict(value = "user:all", allentries = true)}
    )
    public void deletebyid(string id) {
        removebyid(id);
    }

    // 更新数据后刷新缓存
    @caching(
            put = {@cacheput(value = "user:cache", key = "#demo.id", unless = "#result == null")},
            evict = {@cacheevict(value = "user:all", allentries = true)}
    )
    public void updateuser(demo demo) {
        updatebyid(demo);
    }

    @cacheable(value = "user:all")
    public list<demo> listdemo() {
        return list();
    }

}

到此这篇关于浅析springboot整合mybatis如何实现二级缓存的文章就介绍到这了,更多相关springboot mybatis二级缓存内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com