【Redis】SpringBoot+MyBatis集成Redis二级缓存

在pom文件中增加如下依赖

<!--Spring Redis RedisAutoConfiguration-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>3.2.0</version>
</dependency>

spring配置文件application.properties中新增如下配置

#配置redis连接
#因为在我的电脑的hosts文件中已经配置了与CentOS的主机映射关系,在此主机地址可以直接使用CentOS代替
spring.redis.host=CentOS
#redis端口号
spring.redis.port=6379
#连接时间
spring.redis.timeout=5s
#redis连接池参数
spring.redis.lettuce.shutdown-timeout=100ms
#连接池最大连接数(使用负值表示没有限制)默认为8
spring.redis.lettuce.pool.max-active=10
#连接池中最大的空闲连接,默认为8
spring.redis.lettuce.pool.max-idle=8
#连接池最大阻塞等待时间(使用负值表示没有限制)默认-1
spring.redis.lettuce.pool.max-wait=5ms
#连接池中最小空闲连接 默认为0
spring.redis.lettuce.pool.min-idle=1

新增以下类

ApplicationContextHolder.java

/**
* 该接口为标记接口,Spring工厂在初始化时,会自动注入applicationContext
*/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContex;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // this.applicationContex = applicationContext;
        applicationContex = applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContex.getBean(beanName);
    }
}

UserDefineRedisCache.java

/**
 * 自定义redis缓存
 */
public class UserDefineRedisCache implements Cache {
    private Logger logger = LoggerFactory.getLogger(UserDefineRedisCache.class);

    private String id; //存储namespace
    private long timeout = 300; //超时时间
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private RedisTemplate redisTemplate; //(RedisTemplate) ApplicationContextHolder.getBean("redisTemplate");

    public UserDefineRedisCache(String id) {
        this.id = id;
    }

    private RedisTemplate getRedisTemplate() {
        return (RedisTemplate) ApplicationContextHolder.getBean("redisTemplate");
    }

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

    @Override
    public void putObject(Object key, Object value) {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("将查询结果存储到cache.key:" + key + ",value:" + value);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, value, timeout, TimeUnit.SECONDS);
    }

    @Override
    public Object getObject(Object key) {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("从缓存中读取结果.key:" + key);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        return opsForValue.get(key);
    }

    @Override
    public Object removeObject(Object key) {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("从缓存中清除.key:" + key);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        Object value = opsForValue.get(key);
        redisTemplate.delete(key);
        return value;
    }

    @Override
    public void clear() {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("从缓存中清除缓存区所有数据");
        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });
    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }
}

在SpringBoot启动类中加入如下方法

//配置RedisBean
@Bean
public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory connectionFactory) throws UnknownHostException {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(connectionFactory);
    //设置Key、value的序列化
    redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    return redisTemplate;
}

在MyBatis配置文件中开启mybatis二级缓存

<!--
	二级缓存
	type指向我们所定义的redis缓存类
-->
<cache type="com.dora.cache.UserDefineRedisCache">
    <!--设置超时时间-->
    <property name="timeout" value="150"/>
</cache>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@是小白吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值