最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺析SpringBoot整合Mybatis如何實(shí)現(xiàn)二級緩存

 更新時間:2025年05月15日 10:35:10   作者:哪里的破水瓶  
二級緩存,是指多個Sqlsession之間共享數(shù)據(jù),但是也可以使用Redis這樣的緩存作為存儲點(diǎn),但是不支持mybatisplus 里的方法,本文我們就來聊聊SpringBoot整合Mybatis實(shí)現(xiàn)二級緩存的相關(guān)方法吧

mybatis 原生

二級緩存,是指多個Sqlsession之間共享數(shù)據(jù),但是也可以使用Redis這樣的緩存作為存儲點(diǎn)。 但是不支持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) {
            // 是數(shù)組
            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("緩存數(shù)據(jù)格式錯誤");
    }

}

mapper xml

一定要加 cache-ref 才能進(jìn)行二級緩存

<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)) // 默認(rèn)緩存 10 分鐘
                .disableCachingNullValues() // 避免存入控制
                .serializeValuesWith( // 設(shè)置序列化
                        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);
    }

    // 更新數(shù)據(jù)后刷新緩存
    @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();
    }

}

到此這篇關(guān)于淺析SpringBoot整合Mybatis如何實(shí)現(xiàn)二級緩存的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis二級緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

夏津县| 谷城县| 仪征市| 巨野县| 淳安县| 栾城县| 连江县| 黄大仙区| 山东省| 商都县| 卢湾区| 靖边县| 曲阜市| 虞城县| 山东省| 陕西省| 航空| 玉林市| 怀集县| 克山县| 左云县| 尼玛县| 闽清县| 黄冈市| 清涧县| 沿河| 慈溪市| 金华市| 庄河市| 五大连池市| 荣成市| 资中县| 沂源县| 磐石市| 晋城| 寿宁县| 荥经县| 来凤县| 遂平县| 温州市| 筠连县|