欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis整合ehcache做三級緩存的實現(xiàn)方法

 更新時間:2023年06月20日 09:34:47   作者:ThinkPet  
ehcache是一個快速內(nèi)存緩存框架,java項目里用起來很方便,下面這篇文章主要給大家介紹了關于mybatis整合ehcache做三級緩存的實現(xiàn)方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

mybatis整合ehcache做三級緩存

為什么要使用第三級緩存

mybatis二級緩存對細粒度的數(shù)據(jù)級別的緩存實現(xiàn)不好,對同時緩存較多條數(shù)據(jù)的緩存,比如如下需求:

對商品信息進行緩存,由于商品信息查詢訪問量大,且要求用戶每次都能查詢最新的商品信息,此時如果使用mybatis的二級緩存就無法實現(xiàn)---當一個商品變化時只刷新該商品的緩存信息而不刷新其他商品的信息。

因為mybatis的二級緩存區(qū)域以mapper為單位劃分,當一個商品信息變化會將所有商品信息的緩存數(shù)據(jù)全部清空。

解決此類問題需要在業(yè)務層根據(jù)需求對數(shù)據(jù)進行針對性的緩存,即需要使用三級緩存。

原生mybatis整合ehcache做三級緩存

引入mybatis官方提供的依賴mybatis-ehcache

<!-- mybatis-ehcache用的是1.1.0版本-->
<dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.1.0</version>
        </dependency>
<!-- 這里原生mybatis用的是2.1.3版本 -->
 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

在springboot項目的yml配置文件里配置mybatis

要開啟mybatis.configuration.cache-enabled=true

mybatis:
  type-aliases-package: com.example.demo.orm.po
  mapper-locations: classpath:mappers/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
    # 開啟全局緩存(mybatis二級緩存),默認不會開啟,需要程序員配置開啟
    cache-enabled: true

在resources目錄下配置ehcache.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--
       diskStore:為緩存路徑,ehcache分為內(nèi)存和磁盤兩級,此屬性定義磁盤的緩存位置。參數(shù)解釋如下:
       user.home – 用戶主目錄
       user.dir  – 用戶當前工作目錄
       java.io.tmpdir – 默認臨時文件路徑 win7里是 C:\Users\Administrator\AppData\Local\Temp 目錄
     -->
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默認緩存策略,當ehcache找不到定義的緩存時,則使用這個緩存策略。只能定義一個。
     -->
    <!--
      name:緩存名稱。
      maxElementsInMemory:緩存最大數(shù)目
      maxElementsOnDisk:硬盤最大緩存?zhèn)€數(shù)。
      eternal:對象是否永久有效,一但設置了,timeout將不起作用。
      overflowToDisk:是否保存到磁盤,當系統(tǒng)當機時
      timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。
      timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介于創(chuàng)建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
      diskPersistent:是否緩存虛擬機重啟期數(shù)據(jù) Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:這個參數(shù)設置DiskStore(磁盤緩存)的緩存區(qū)大小。默認是30MB。每個Cache都應該有自己的一個緩沖區(qū)。
      diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
      memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據(jù)指定的策略去清理內(nèi)存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。
      clearOnFlush:內(nèi)存數(shù)量最大時是否清除。
      memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數(shù))。
      FIFO,first in first out,這個是大家最熟的,先進先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。
      LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現(xiàn)有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
   -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="true"
            diskPersistent="true"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

在需要使用ehcache緩存的mapper.xml里配置cache標簽

如:在AccountMapper.xml里配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.orm.dao.AccountMapper">
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!--  ehcache 用作mybatis的三級緩存時
,只會對select語句進行緩存,每次遇到其他語句如insert,update,delete則會清空緩存
 即:新插入的數(shù)據(jù),或修改的數(shù)據(jù),只有當立即select時,會緩存到Ehcache中。
 select 結(jié)果緩存到Ehcache后,再次查詢相同數(shù)據(jù)時,會命中Ehcache緩存;
 Ehcache默認配置是LRU, 緩存的內(nèi)容是 最近最少使用的 ,
 緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,
 那么現(xiàn)有緩存元素中時間戳離當前時間最遠的元素將被清出緩存
 -->
    <resultMap id="BaseResultMap"
               type="com.example.demo.orm.po.Account">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="username" jdbcType="VARCHAR" property="username"/>
        <result column="password_ciper" jdbcType="VARCHAR" property="passwordCiper"/>
    </resultMap>
    <select id="findOneById" resultMap="BaseResultMap">
        select * from t_account where id = #{id}
    </select>
    <select id="selectUserList"
            parameterType="com.example.demo.orm.po.Account"
            resultMap="BaseResultMap">
        select * from t_account
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="username != null and username != '' ">
                and username = #{username}
            </if>
            <if test="passwordCiper != null and passwordCiper != '' ">
                and password_ciper = #{passwordCiper}
            </if>
        </where>
    </select>
    <insert id="insertOne"
            useGeneratedKeys="true"
            keyProperty="id"
            parameterType="com.example.demo.orm.po.Account">
       insert into t_account(username,password_ciper)
        values (#{username},#{passwordCiper})
    </insert>
</mapper>

測試Ehcache緩存效果

 @Test
    void test81902(){
        //連續(xù)執(zhí)行2次相同的select操作
        System.out.println(accountMapper.findOneById(17));
        System.out.println(accountMapper.findOneById(17));
}

2023-06-19 19:51:41.924  INFO 6356 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-06-19 19:51:42.186  INFO 6356 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1502971166 wrapping com.mysql.cj.jdbc.ConnectionImpl@48a2db72] will not be managed by Spring
==>  Preparing: select * from t_account where id = ?
==> Parameters: 17(Integer)
<==    Columns: id, username, password, password_ciper
<==        Row: 17, ert, sgvf23t, 1a9777393e7fda54
<==      Total: 1
2023-06-19 19:51:42.452  INFO 6356 --- [           main] c.e.demo.plugin.EncryptDecryptUtil       : passwordCiper字段需要解密,1a9777393e7fda54解密后的值是sgvf23t
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@518ddd3b]
Account(id=17, username=ert, password=sgvf23t, passwordCiper=sgvf23t)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@72443081] was not registered for synchronization because synchronization is not active
Cache Hit Ratio [com.example.demo.orm.dao.AccountMapper]: 0.5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@72443081]
Account(id=17, username=ert, password=sgvf23t, passwordCiper=sgvf23t)

Cache Hit Ratio [com.example.demo.orm.dao.AccountMapper]: 0.5

意思是緩存命中了AccountMapper,命中率0.5

總結(jié)

到此這篇關于mybatis整合ehcache做三級緩存的實現(xiàn)方法的文章就介紹到這了,更多相關mybatis整合ehcache三級緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java groovy內(nèi)存回收測試步驟解析

    Java groovy內(nèi)存回收測試步驟解析

    這篇文章主要介紹了Java groovy內(nèi)存回收測試步驟解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • IntelliJ IDEA 2020.2正式發(fā)布,兩點多多總能助你提效

    IntelliJ IDEA 2020.2正式發(fā)布,兩點多多總能助你提效

    這篇文章主要介紹了IntelliJ IDEA 2020.2正式發(fā)布,諸多亮點總有幾款能助你提效,本文通過圖文實例代碼相結(jié)合給大家介紹的非常詳細,需要的朋友可以參考下
    2020-07-07
  • Maven優(yōu)雅的添加第三方Jar包的方法

    Maven優(yōu)雅的添加第三方Jar包的方法

    下面小編就為大家?guī)硪黄狹aven優(yōu)雅的添加第三方Jar包的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • java后端請求過濾options方式

    java后端請求過濾options方式

    Optional項是一個容器對象,它可以包含非空值,也可以不包含非空值,它用于表示沒有值,而不是使用?null,引入Optional項是為了幫助開發(fā)人員編寫更簡潔、更具表現(xiàn)力的代碼,并避免?NullPointerException
    2024-01-01
  • SpringBoot如何加載多個YAML配置文件

    SpringBoot如何加載多個YAML配置文件

    在Spring?Boot中加載多個?YAML?配置文件是一個常見的需求,通常用于將配置信息分離到多個文件中以便于管理和維護,下面就跟隨小編一起來看看具體實現(xiàn)吧
    2025-02-02
  • spring security動態(tài)配置url權(quán)限的2種實現(xiàn)方法

    spring security動態(tài)配置url權(quán)限的2種實現(xiàn)方法

    對于使用spring security來說,存在一種需求,就是動態(tài)去配置url的權(quán)限,即在運行時去配置url對應的訪問角色。下面這篇文章主要給大家介紹了關于spring security動態(tài)配置url權(quán)限的2種實現(xiàn)方法,需要的朋友可以參考下
    2018-06-06
  • Java利用隨機分錢模擬財富變化

    Java利用隨機分錢模擬財富變化

    這篇文章主要為大家詳細介紹了Java如何利用隨機分錢思想模擬財富的變化,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2022-12-12
  • Eclipse中實現(xiàn)JS代碼提示功能(圖文教程)

    Eclipse中實現(xiàn)JS代碼提示功能(圖文教程)

    本文通過圖文并茂的形式給大家介紹了Eclipse中實現(xiàn)JS代碼提示功能,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
    2017-11-11
  • IntelliJ IDEA2020.1版本更新pom文件自動導包的方法

    IntelliJ IDEA2020.1版本更新pom文件自動導包的方法

    這篇文章主要介紹了IntelliJ IDEA2020.1版本更新pom文件自動導包的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06
  • Spring?Data?JPA關系映射@OneToOne實例解析

    Spring?Data?JPA關系映射@OneToOne實例解析

    這篇文章主要為大家介紹了Spring?Data?JPA關系映射@OneToOne實例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08

最新評論