springboot开启mybatis二级缓存

我的项目版本号如下:

   <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

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ADRU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值