学无先后,达者为师

网站首页 编程语言 正文

springboot开启mybatis二级缓存

作者:ADRU 更新时间: 2024-02-16 编程语言

我的项目版本号如下:

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

首先选一个缓存框架(EhCache )EhCache 是一个广泛使用的开源 Java 分布式缓存库,主要用于提高应用程序的性能,减少数据库访问次数,通过缓存频繁读取的数据来实现。它可以作为 Hibernate、Spring、MyBatis 等框架的缓存提供者,用于提升这些框架在数据处理方面的性能。可以缓存来自数据库的数据,当应用程序需要这些数据时,可以直接从缓存中读取,而不是每次都查询数据库。这减少了数据库的访问压力和响应时间。

第一步导入依赖

   <!-- mybatis 二级缓存使用-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.8</version>
        </dependency>

第二步编写配置文件

src/main/resources 目录下创建一个名为 ehcache.xml 的 EhCache 配置文件。这个文件用于定义缓存的具体参数,例如缓存策略、生命周期等:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd">

    <cache name="default"
           maxEntriesLocalHeap="10000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU">
    </cache>
</ehcache>

 第三步加注解

对于 Mapper 接口,可以通过在接口上添加 @CacheNamespace 注解开启二级缓存

如下:

import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Mapper;

@Mapper
@CacheNamespace
public interface YourMapper {
    // 方法定义
}

 第四步修改配置文件

application.properties

spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml

application.yml

spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

原文链接:https://blog.csdn.net/m0_71507863/article/details/136113026

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新