0
点赞
收藏
分享

微信扫一扫

Springboot + Mybatis + Redis 实现二级缓存功能

1.使用redis 实现mybaits 的二级缓存功能:
使用Redis实现二级缓存,将运行结果存放在redis当中,以便多次查询时,可以直接在内存中直接获取。

2.项目配置目录构成:



运行环境为
springboot: 2.0.1
redis: 3.2.100
mybatis: 3.5.2
mysql 5.7
java 1.8.0_152

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


HunterMapper.xml文件:


Mybaits-confi.xml 文件:


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):


4.2 Controller:


4.3 Mapper:


4.4 Service:
在service层中,需要添加 @Cacheable 注解使返回的值存放在cache当中


5.运行:
再加上启动类Start的实现(注意,在Start类中需要添加 @EnableCaching 以启用缓存机制):


启动redis :
./redis/redis-server.sh
./redis/redis-cli.sh

在浏览器中输入url进行验证:


执行
127.0.0.1:6397> keys *
查看执行后的缓存数据

具体代码:https://github.com/mushroomcode/bounce12

举报

相关推荐

0 条评论