MyBatis-plus二級緩存使用

MyBatis二級緩存使用

  • 注意點:
  • 在最新的3.x版本,實現二級緩存的配置也有了一些改變。
  • 官方建議在service使用緩存,可是你也能夠直接在mapper層緩存,這裏的二級緩存就是直接在Mapper層進行緩存操做redis

    Mybatis的二級緩存實現也十分簡單,只要在springboot的配置文件打開二級緩存,即

mybatis-plus:
  configuration:
    cache-enabled: true

緩存接口的實現

public class MybatisRedisCache implements Cache {


    // 讀寫鎖
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    //這裏使用了redis緩存,使用springboot自動注入
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private String id;

    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

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

    @Override
    public void putObject(Object key, Object value) {
        if (redisTemplate == null) {
        //因爲啓動期間注入失敗,只能運行期間注入,這段代碼能夠刪除
            redisTemplate = (RedisTemplate<String, Object>) ApplicationContextRegister.getApplicationContext().getBean("RedisTemplate");
        }
        if (value != null) {
            redisTemplate.opsForValue().set(key.toString(), value);
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            if (key != null) {
                return redisTemplate.opsForValue().get(key.toString());
            }
        } catch (Exception e) {
            log.error("緩存出錯 ");
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        if (key != null) {
            redisTemplate.delete(key.toString());
        }
        return null;
    }

    @Override
    public void clear() {
        log.debug("清空緩存");
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate<String, Object>) ApplicationContextRegister.getApplicationContext().getBean("functionDomainRedisTemplate");
        }
        Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    @Override
    public int getSize() {
        Long size = redisTemplate.execute((RedisCallback<Long>) RedisServerCommands::dbSize);
        return size.intValue();
    }

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

mapper.xml文件聲明緩存,這裏3.x只須要這樣配置

<?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.zsy.mapper.CarouselMapper">
    <cache-ref namespace="com.zsy.mapper.CarouselMapper"/>
</mapper>
Mapper接口使用註解
@Repository
@CacheNamespace(implementation=MybatisRedisCache.class,eviction=MybatisRedisCache.class)
public interface CarouselMapper extends BaseMapper<Carousel> {}
相關文章
相關標籤/搜索