Springboot + Mybatis + Redis 實(shí)現(xiàn)二級緩存功能

1.使用redis 實(shí)現(xiàn)mybaits 的二級緩存功能:
使用Redis實(shí)現(xiàn)二級緩存,將運(yùn)行結(jié)果存放在redis當(dāng)中,以便多次查詢時(shí),可以直接在內(nèi)存中直接獲取。

2.項(xiàng)目配置目錄構(gòu)成:


屏幕截圖(103).png

運(yùn)行環(huán)境為
springboot: 2.0.1
redis: 3.2.100
mybatis: 3.5.2
mysql 5.7
java 1.8.0_152

3.配置文件:
application-yml文件:


屏幕截圖(112).png

HunterMapper.xml文件:


屏幕截圖(113).png

Mybaits-confi.xml 文件:


屏幕截圖(114).png

maven配置(pom):

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
        <version>2.0.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>

4.springboot的代碼:
4.1 測試用的Bean(HunterImpl):


屏幕截圖(116).png

4.2 Controller:


屏幕截圖(118).png

4.3 Mapper:


屏幕截圖(115).png

4.4 Service:
在service層中,需要添加 @Cacheable 注解使返回的值存放在cache當(dāng)中


屏幕截圖(117).png

5.運(yùn)行:
再加上啟動(dòng)類Start的實(shí)現(xiàn)(注意,在Start類中需要添加 @EnableCaching 以啟用緩存機(jī)制):


屏幕截圖(119).png

啟動(dòng)redis :
./redis/redis-server.sh
./redis/redis-cli.sh

在瀏覽器中輸入url進(jìn)行驗(yàn)證:


屏幕截圖(121).png

執(zhí)行
127.0.0.1:6397> keys *
查看執(zhí)行后的緩存數(shù)據(jù)

具體代碼:https://github.com/mushroomcode/bounce12

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容