SpringBoot2.0 自定义redis缓存管理器

本文介绍了如何在SpringBoot2.0中自定义Redis缓存管理器,包括导包、配置类的设置,以及启动类启用 caching 的步骤。文中提供了一个简单的示例,展示了默认缓存SimpleCacheManager和RedisCacheManager的应用。
摘要由CSDN通过智能技术生成

自定义redis缓存管理器

1、导包

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

2、配置类

package com.atguigu.cache.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.time.Duration;

/**
 * @author Mr.Z
 * @create 2019/8/7 15:20
 * key多了一个前缀
 */
@Configuration
public class MyRedisConfig {

    //过期时间1天
    private Dur
MyBatis Plus提供了默认的Redis缓存管理器,但是有时候我们需要根据自己的业务需求来定制一个适合自己的缓存管理器,这里简单介绍一下如何自定义Redis缓存管理器: 1. 实现Cache接口 首先需要实现MyBatis的Cache接口,该接口定义了缓存操作的基本接口方法。可以参考默认的RedisCache实现。 ``` public interface Cache { String getId(); void putObject(Object key, Object value); Object getObject(Object key); Object removeObject(Object key); void clear(); int getSize(); default void putObject(Object key, Object value, long ttl) { throw new UnsupportedOperationException("not support"); } } ``` 2. 实现CacheManager接口 接着需要实现MyBatis的CacheManager接口,该接口负责管理各个缓存实例的生命周期以及提供创建缓存的方法。可以参考默认的RedisCacheManager实现。 ``` public interface CacheManager { Cache getCache(String var1); void addCache(String var1); Set<String> getCacheNames(); default void destroy() { } } ``` 3. 配置缓存管理器 在MyBatis的配置文件中配置自定义缓存管理器缓存实现类。可以像下面这样配置: ``` <cache type="com.example.MyCacheManager"> <!-- 缓存过期时间,单位:秒,默认为永不过期 --> <property name="ttl" value="3600"></property> <!-- RedisHost --> <property name="host" value="localhost"></property> <!-- RedisPort --> <property name="port" value="6379"></property> <!-- RedisPassword --> <property name="password" value=""></property> <!-- RedisDatabase --> <property name="database" value="0"></property> <!-- RedisTimeout --> <property name="timeout" value="5000"></property> </cache> ``` 其中type属性值为自定义的CacheManager实现类。 4. 使用缓存 在Mapper接口方法上使用@CacheNamespace注解开启缓存功能并指定缓存管理器,例如: ``` @Mapper @CacheNamespace(implementation = MyCacheManager.class) public interface UserMapper { @Select("select * from user where id = #{id}") @Options(useCache = true, flushCache = Options.FlushCachePolicy.FALSE) User selectById(@Param("id") int id); } ``` 这样就可以在查询User对象时自动使用自定义Redis缓存管理器进行缓存
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值