溫馨提示×

MyBatis在Spring Boot中的緩存機制如何使用

小樊
81
2024-09-11 20:03:38
欄目: 編程語言

MyBatis 在 Spring Boot 中提供了一級緩存和二級緩存。一級緩存是默認開啟的,而二級緩存需要手動配置。下面分別介紹這兩種緩存的使用方法。

  1. 一級緩存

一級緩存是 SqlSession 級別的緩存,它的生命周期與 SqlSession 相同。當在同一個 SqlSession 中執(zhí)行相同的查詢語句時,MyBatis 會優(yōu)先從一級緩存中獲取結果,而不是直接從數(shù)據(jù)庫查詢。這樣可以提高查詢性能,減少與數(shù)據(jù)庫的交互次數(shù)。

一級緩存的使用方法很簡單,只需要在 MyBatis 的映射文件中編寫相應的查詢語句即可。例如:

    SELECT * FROM user WHERE id = #{id}
</select>

當執(zhí)行這個查詢語句時,MyBatis 會自動將結果存入一級緩存。

  1. 二級緩存

二級緩存是全局的緩存,它的生命周期與 Spring 容器相同。當多個 SqlSession 執(zhí)行相同的查詢語句時,MyBatis 會優(yōu)先從二級緩存中獲取結果,而不是直接從數(shù)據(jù)庫查詢。這樣可以進一步提高查詢性能,減少與數(shù)據(jù)庫的交互次數(shù)。

二級緩存的使用方法如下:

首先,在 MyBatis 的映射文件中添加` 標簽,以啟用二級緩存:

<mapper namespace="com.example.UserMapper">
   <cache type="org.mybatis.caches.ehcache.EhCacheCache" eviction="FIFO" flushInterval="60000" size="100" readOnly="false"/>
    ...
</mapper>

其中,type 屬性指定了緩存實現(xiàn)類,這里使用 EhCache;eviction 屬性指定了緩存淘汰策略,這里使用先進先出(FIFO);flushInterval 屬性指定了緩存刷新間隔,這里設置為 60 秒;size 屬性指定了緩存大小,這里設置為 100;readOnly 屬性指定了緩存是否只讀,這里設置為 false。

然后,在 Spring Boot 的配置文件中添加 EhCache 的配置:

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

最后,創(chuàng)建 EhCache 的配置文件 ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="java.io.tmpdir/ehcache" />
   <defaultCache
            maxElementsInMemory="100"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
   <cache name="com.example.UserMapper"
           maxElementsInMemory="100"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           overflowToDisk="true"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU"
    />
</ehcache>

這樣,就完成了 MyBatis 在 Spring Boot 中的二級緩存配置。當執(zhí)行相同的查詢語句時,MyBatis 會自動將結果存入二級緩存。

0