redis集成 mybatis缓存实现

项目地址:https://download.csdn.net/download/kk12927/12439285
需要修改yml里的自己的服务器ip和地址,和数据库

一、依赖

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

        <!--生成getset-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

<!--        操作redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<!--        redis session管理-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

二、配置yml



spring:
  datasource:
    username: root
    password: 123456
    #mysql8版本以上的驱动包,需要指定以下时区
    url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2B8
    #mysql8版本以上指定新的驱动类
    driver-class-name: com.mysql.cj.jdbc.Driver
    #引入Druid数据源
    type: com.alibaba.druid.pool.DruidDataSource

    #   数据源其他配置, DataSourceProperties中没有相关属性,默认无法绑定
    initialSize: 8
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,logback
    maxPoolPreparedStatementPerConnectionSize: 25
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500



  redis:
    host: 47.96.xx.xx  #如果启用哨兵注释掉
    port: 6379     #如果启用哨兵注释掉
    database: 0
#    如果使用哨兵
  #  sentinel:
    #  master: aa  #哨兵名称
     # nodes: 192.168.220.326379 # 启动的服务器


  #redis管理session
  session:
    store-type: redis

  #配置mybatis相关文件路径
mybatis:
  #映射配置文件路径
  mapper-locations: classpath:mybatis/mapper/*.xml
  #核心配置文件路径
  config-location: classpath:mybatis/mybatis-config.xml
server:
  port: 18888

logging:
  level:
    root: info
    com.ck.springboot.mapper: debug


三、目录结构

在这里插入图片描述

四、重点文件分析

1.实现mybatis的缓存接口,springboot->cache->RedisCache,主要目的是使用mybatis缓存时,使用redis缓存。

package com.ck.springboot.cache;

import com.ck.springboot.util.ApplicationContextUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedisCache implements Cache {
    private String id;

    public RedisCache (String id){
        System.out.println("当前加缓存的namespace id" + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    /**
     * 放入缓存
     * @param o
     * @param o1
     */
    @Override
    public void putObject(Object o, Object o1) {
        System.out.println("key:" + o);
        System.out.println("value:" + o1);
        //获取对象
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        //存储缓存数据d
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        //hash模型
        redisTemplate.opsForHash().put(id.toString(),o.toString(),o1);


        if(id.toString().equals("com.ck.springboot.entities.User")){
            redisTemplate.expire(id.toString(),10, TimeUnit.DAYS);
        }
        if(id.toString().equals("com.ck.springboot.entities.xxx")){
            redisTemplate.expire(id.toString(),10, TimeUnit.HOURS);
        }
    }

    /**
     * 在缓存中获取
     * @param
     * @return
     */
    @Override
    public Object getObject(Object o) {
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        //存储缓存数据
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        return redisTemplate.opsForHash().get(id.toString(),o.toString());
    }

    /**
     * 删除缓存中数据
     * @param
     * @return
     */
    @Override
    public Object removeObject(Object o) {
        System.out.println("删除缓存");
        return null;
    }

    /**
     * 清空缓存
     */
    @Override
    public void clear() {
        System.out.println("清空缓存");
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        //存储缓存数据
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //清空当前namespace对应map
        redisTemplate.delete(id.toString());
    }

    /**
     * 缓存命中概率
     * @return
     */
    @Override
    public int getSize() {
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        //存储缓存数据
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //获取当前namespace中缓存数据
        return redisTemplate.opsForHash().size(id.toString()).intValue();
    }
}

2.在resources->myBatis->mybatis-config.xml配置信息。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--核心配置文件-->
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

3.在resources->myBatis->mapper->UserMapper.xml使用 mybatis二级缓存。

<?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.ck.springboot.mapper.UserMapper">

<!--    开启二级缓存 mybatis二级缓存默认开局开启 cacheEnabled true 默认值
        type : 指定自定义cache全限定名
-->
    <cache type="com.ck.springboot.cache.RedisCache"></cache>



    <select id="findAll" resultType="com.ck.springboot.entities.User">
        select * from user
    </select>


    <select id="find" resultType="com.ck.springboot.entities.User" parameterType="String">
        select * from user where username=#{username}
    </select>

    <insert id="save" parameterType="com.ck.springboot.entities.User">
        insert into user  (username,password) values(#{username},#{password})
    </insert>

    <update id="update" parameterType="com.ck.springboot.entities.User">
        update user set username=#{username} , password=#{password} where id=#{id}
    </update>

    <delete id="delete" parameterType="String">
        delete from user where id=#{id}
    </delete>


</mapper>

五、session共享问题

1.引入依赖

  <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

2.在springboot->config->RedisSessionManager配置文件

package com.ck.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@Configuration
@EnableRedisHttpSession  //开启全局redisSession会话管理
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1000,redisNamespace = "redis:session")  //过期时间,修改redis里保存的key名称
public class RedisSessionManager {
}

3.更改resources->myBatis->mapper->UserMapper.xml里的缓存标签,使用cache-ref。

<?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.ck.springboot.mapper.UserMapper">



<!--    作用:共享缓存,将本模块的缓存指定缓存到com.ck.springboot.mapper.xxxMapper模块中,如果用这个标签,就不用cache标签-->
    <cache-ref namespace="com.ck.springboot.mapper.xxxMapper"></cache-ref>

    <select id="findAll" resultType="com.ck.springboot.entities.User">
        select * from user
    </select>


    <select id="find" resultType="com.ck.springboot.entities.User" parameterType="String">
        select * from user where username=#{username}
    </select>

    <insert id="save" parameterType="com.ck.springboot.entities.User">
        insert into user  (username,password) values(#{username},#{password})
    </insert>

    <update id="update" parameterType="com.ck.springboot.entities.User">
        update user set username=#{username} , password=#{password} where id=#{id}
    </update>

    <delete id="delete" parameterType="String">
        delete from user where id=#{id}
    </delete>


</mapper>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值