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到此这篇关于springboot开启mybatis二级缓存的步骤详解的文章就介绍到这了,更多相关springboot开启mybatis缓存内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot返回前端Long类型字段丢失精度问题及解决方案
Java服务端返回Long整型数据给前端,JS会自动转换为Number类型,本文主要介绍了SpringBoot返回前端Long类型字段丢失精度问题及解决方案,感兴趣的可以了解一下2024-03-03
spring boot security自定义认证的代码示例
这篇文章主要介绍了spring boot security自定义认证,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-07-07


最新评论