SpringBoot和redis 实现(mybatis的)分布式缓存

redis分布式缓存(搭建环境)

引入依赖

 <dependencies>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>
            <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>

搭建mybatis和springboot的环境

server.port=8888
spring.redis.host=127.0.0.1
spring.redis.port=6379

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mp?useSSL=true&serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=true

mybatis.type-aliases-package=com.aaa.pojo
mybatis.mapper-locations=classpath:/mapper/*.xml
logging.level.com.aaa.mapper=debug

Dao层

@Repository
public interface UserMapper {
    public List<Users> findAll();
}

mapepr文件

<?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.aaa.mapper.UserMapper">
    <cache/>  //开启二级缓存
    <select id="findAll" resultType="com.aaa.pojo.Users">

         select * from users

    </select>
</mapper>

测试环境是否搭建成功

@SpringBootTest
public class UsersTest {

    @Autowired
    private UserService userService;

    @Test
    public  void  test(){

       // Cache cache;
        List<Users> all = userService.findAll();
        System.out.println(all);
        System.out.println("==================");
        List<Users> all1 = userService.findAll();
        System.out.println(all1);
    }
}

Cache接口

package org.apache.ibatis.cache;

import java.util.concurrent.locks.ReadWriteLock;


public interface Cache {
  String getId();
  Object getObject(Object key);
  Object removeObject(Object key);
  void clear();
  int getSize();
  default ReadWriteLock getReadWriteLock() {
    return null;
  }

}

注意:mybatis中默认实现了org.apache.ibatis.cache.impl.PerpetualCache的缓存机制

<Cache  type="org.apache.ibatis.cache.impl.PerpetualCache"/> 默认实现

现在我们要用Redis实现缓存:

Redis分布式缓存(二)

由mybatis默认实现缓存的原理可知 我们要用Redis实现缓存,需要我们自定义缓存并实现Cache接口

package com.aaa.config;

import com.aaa.utils.ApplicationContextUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashMap;
import java.util.Map;

/*
*  自定义Redis缓存实现
* */

public class RedisCache implements Cache {
    //当前放入缓存的mapper的namespace
    private final String id;

    //将缓存放入Redis中
    public RedisCache(String id) {

        this.id = id;
    }
    //返回Cache的唯一标识
    @Override
    public String getId() {
        return id;
    }

   /**
   * 缓存放入值
   * */
    @Override
    public void putObject(Object key, Object value) {

        //通过applicationContext工具类来获取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");

        //序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //使用Redis中的hash类型作为缓存
        HashOperations forHash = redisTemplate.opsForHash();
        forHash.put(id.toString(),key.toString(),value);
    }

    /**
     *获取值
     */
    @Override
    public Object getObject(Object key) {
        //通过applicationContext工具类来获取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");

        //序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //使用Redis中的hash类型作为缓存
        HashOperations forHash = redisTemplate.opsForHash();

        Object o = forHash.get(id.toString(), key.toString());
        return  o;
    }


    @Override
    public Object removeObject(Object key) {
        return null;
    }

	//清空缓存  默认增删改会清除缓存
    @Override
    public void clear() {
	//通过applicationContext工具类来获取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");

        //序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.delete(id.toString());
    }


    @Override
    public int getSize() {
        //通过applicationContext工具类来获取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");

        //序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //使用Redis中的hash类型作为缓存
        HashOperations forHash = redisTemplate.opsForHash();
			//获取hash中键的长度
        return  forHash.size(id.toString()).intValue();
    }
}

applicationContext工具类

package com.aaa.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration //标注是一个配置类
public class ApplicationContextUtils implements ApplicationContextAware {

    public  static  ApplicationContext applicationContext;
    //将上下文对象赋值给声明的属性
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    //redisTemplate通过上下文应用程序来获取
    //注入到工厂中,我们就可以通过传入名称来获取他的实例
    public  static  Object getBean(String name){
         return   applicationContext.getBean(name);
    }
}
<?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.aaa.mapper.UserMapper">
	<!-- 开启缓存并指定缓存的类型-->
    <cache type="com.aaa.config.RedisCache"/>
    <select id="findAll" resultType="com.aaa.pojo.Users">

         select * from users

    </select>
</mapper>

测试:

@SpringBootTest
public class UsersTest {

    @Autowired
    private UserService userService;

    @Test
    public  void  test(){

        List<Users> all = userService.findAll();
        System.out.println(all);
        System.out.println("==================");
        List<Users> all1 = userService.findAll();
        System.out.println(all1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值