redis二級緩存設置-SpringBoot

1.pom.xml導入依賴

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

2.bootstrap.yml開啓緩存,配置數據庫和redis基本信息

mybatis:
  configuration:
    cache-enabled: true
datasource:
  druid:
spring:
  redis:

3.mapper.xml添加緩存映射

<mapper ......>

        <cache type=".....RedisCache"/>

或者

mapper.class

@CacheNamespace(implementation = RedisCache.class)

4.RedisCache.class緩存操作類

public class RedisCache implements Cache {
    private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
    //緩存對象唯一標識
    private final String id; 
    //用於事務性緩存操作的讀寫鎖
    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 
    //操作數據緩存
    private  RedisTemplate redisTemplate;  
    //緩存對象的是失效時間,30分鐘
    private static final long EXPRIRE_TIME_IN_MINUT = 30;
    //構造方法---把對象唯一標識傳進來
    public RedisCache(String id){
        if(id == null){
            throw new IllegalArgumentException("緩存對象id是不能爲空的");
        }
        this.id = id;
    }
    @Override
    public String getId() {
        return this.id;
    }
    //給模板對象RedisTemplate賦值,並傳出去
    private RedisTemplate getRedisTemplate(){
        if(redisTemplate == null){    //每個連接池的連接都要獲得RedisTemplate
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }
    //保存緩存對象的方法
    @Override
    public void putObject(Object key, Object value) {
        try{
            RedisTemplate redisTemplate = getRedisTemplate();
            //使用redisTemplate得到值操作對象
            ValueOperations operation = redisTemplate.opsForValue();
            //使用值操作對象operation設置緩存對象
            operation.set(key,value,EXPRIRE_TIME_IN_MINUT, TimeUnit.MINUTES);  
            logger.debug("緩存對象保存成功");
        }catch (Throwable t){
            logger.error("緩存對象保存失敗"+t);
        } 
    }
    //獲取緩存對象的方法
    @Override
    public Object getObject(Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            ValueOperations operations = redisTemplate.opsForValue();
            Object result = operations.get(key);
            logger.debug("獲取緩存對象");
            return result;
        }catch (Throwable t){
            logger.error("緩存對象獲取失敗"+t);
            return null;
        }
    }
    //刪除緩存對象
    @Override
    public Object removeObject(Object key) {
        try{
            RedisTemplate redisTemplate = getRedisTemplate();
            redisTemplate.delete(key);
            logger.debug("刪除緩存對象成功!");
        }catch (Throwable t){
            logger.error("刪除緩存對象失敗!"+t);
        }
        return null;
    }
    //清空緩存對象
    //當緩存的對象更新了的化,就執行此方法
    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        //回調函數
        redisTemplate.execute((RedisCallback)collection->{
            collection.flushDb();
            return  null;
        });
        logger.debug("清空緩存對象成功!");
    }
    //可選實現的方法
    @Override
    public int getSize() {
        return 0;
    } 
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
 }

5.ApplicationContextHolder注入緩存Bean

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext ctx;
    @Override
    //向工具類注入applicationContext
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext; 
    }
    public static ApplicationContext getCtx(){
        return ctx;
    }
    public static <T> T getBean(Class<T> tClass){
        return ctx.getBean(tClass);
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        return (T) ctx.getBean(name);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章