(改造)mybatis+spring与redis整合的优雅实现

针对MyBatis的Redis缓存扩展库存在的问题,如配置繁琐且不支持集群等,本文提出了一种改进方案。通过重写RedisCache组件并利用Spring Data Redis的RedisTemplate,实现了更简洁、易读且易于集成的缓存解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mybatis的redis缓存扩展库已经n久没有更新过了,最新的还是1.0.0-betal2 版本。

mybatis redis扩展存在很多问题,比如,他需要你单独配置redis的为他配置单独的redis配置信息,不支持集群,很挫,我们可以把他的RedisCache重写下,使用RedisTemplate来写,简化代码,增加可读性,与项目浑然一体统一配置


import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *
 * @Title:
 * @Description:
 * @author: hollowJ
 * @date: 2016/11/21
 * @version: V1.0.0
 */

/**
 * Cache adapter for Redis.
 *
 * @author Eduardo Macarron
 */
public final class RedisCache2 implements Cache {

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private String id;
    private RedisConnectionFactory redisConnectionFactory;
    private RedisTemplate<String, Object> redisTemplate;

    public RedisCache2(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 int getSize() {
        return Integer.valueOf(getRedisTemplate().opsForHash().size(id).toString());
    }

    @Override
    public void putObject(final Object key, final Object value) {
        getRedisTemplate().opsForHash().put(id, key, value);
    }

    @Override
    public Object getObject(final Object key) {
        return getRedisTemplate().opsForHash().get(id, key);
    }

    @Override
    public Object removeObject(final Object key) {
        return getRedisTemplate().opsForHash().delete(id, key);
    }

    @Override
    public void clear() {
        getRedisTemplate().opsForHash().delete(id);

    }

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

    @Override
    public String toString() {
        return "Redis {" + id + "}";
    }


    private RedisTemplate<String, Object> getRedisTemplate() {
        WebApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        return (RedisTemplate<String, Object>) currentWebApplicationContext.getBean("redisTemplate");
    }
}

 

转载于:https://my.oschina.net/hollowj/blog/792101

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值