MyBatis-RedisCache源码分析

回顾

在前面,我们通过 redis​ 集成了 MyBatis​ 的二级缓存,MyBatis的二级缓存整合redis ,接下来,我们来分析一下 RedisCache​ 的源码。

源码分析

RedisCache 主要是通过实现 Cache 接口来做的。数据存储和获取主要是通过操作 jedis 来实现。

public final class RedisCache implements Cache {
    private final ReadWriteLock readWriteLock = new DummyReadWriteLock();
    private String id;
    private static JedisPool pool;

    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        } else {
            this.id = id;
            RedisConfig redisConfig = RedisConfigurationBuilder.getInstance().parseConfiguration();
            pool = new JedisPool(redisConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getConnectionTimeout(), redisConfig.getSoTimeout(), redisConfig.getPassword(), redisConfig.getDatabase(), redisConfig.getClientName());
        }
    }
}

RedisCache 在 MyBatis 启动的时候由 MyBatis 的 CacheBuilder​ 构建,构建的方式就是调用 Cache​ 实现类的带 id​ 参数的构造方法。

// CacheBuilder.java

public Cache build() {
    setDefaultImplementations();
    Cache cache = newBaseCacheInstance(implementation, id);
    setCacheProperties(cache);
}

private Cache newBaseCacheInstance(Class<? extends Cache> cacheClass, String id) {
    Constructor<? extends Cache> cacheConstructor = getBaseCacheConstructor(cacheClass);
    try {
        return cacheConstructor.newInstance(id);
    } catch (Exception e) {
        throw new CacheException("Could not instantiate cache implementation (" + cacheClass + "). Cause: " + e, e);
    }
}

RedisCache​ 的构造方法中,调用了 RedisConfigurationBuilder​ 来常见 RedisConfig​ 对象,并通过 RedisConfig​ 对象来创建 Jedis​ 。

RedisConfig​ 继承了 JedisPoolConfig​ ,并定义了一些属性来读取配置。

public class RedisConfig extends JedisPoolConfig {
    private String host = "localhost";
    private int port = 6379;
    private int connectionTimeout = 2000;
    private int soTimeout = 2000;
    private String password;
    private int database = 0;
    private String clientName;
}

RedisConfig​ 是由 RedisConfigurationBuilder​​ 构建的,这个类的主要方法是 parseConfiguration

public RedisConfig parseConfiguration(ClassLoader classLoader) {
    Properties config = new Properties();
    InputStream input = classLoader.getResourceAsStream(this.redisPropertiesFilename);
    if (input != null) {
        try {
            config.load(input);
        } catch (IOException var12) {
            throw new RuntimeException("An error occurred while reading classpath property '" + this.redisPropertiesFilename + "', see nested exceptions", var12);
        } finally {
            try {
                input.close();
            } catch (IOException var11) {
            }

        }
    }

    RedisConfig jedisConfig = new RedisConfig();
    this.setConfigProperties(config, jedisConfig);
    return jedisConfig;
}

该方法从 Resource​ 读取一个 redis.properties​ 文件,其结构如下:

host=localhost
port=6379
password=123456
database=0

读取完成之后将内容设置到 RedisConfig 对象中。

接下来,RedisCache 使用 RedisCo 创建 Jedis。在 RedisCache 中,实现了一个简单的模板方法来操作 redis:

private Object execute(RedisCallback callback) {
    Jedis jedis = pool.getResource();

    Object var3;
    try {
        var3 = callback.doWithRedis(jedis);
    } finally {
        jedis.close();
    }

    return var3;
}

目标接口为 RedisCallback,该接口定义了一个简单的 doWithRedis 方法用来进行 redis 相关操作:

public interface RedisCallback {
    Object doWithRedis(Jedis var1);
}

接下来,我们分析一下 Cache 中的两个重要方法 putObject()和 getObject()

public void putObject(final Object key, final Object value) {
    this.execute(new RedisCallback() {
        public Object doWithRedis(Jedis jedis) {
            jedis.hset(RedisCache.this.id.toString().getBytes(), key.toString().getBytes(), SerializeUtil.serialize(value));
            return null;
        }
    });
}
public Object getObject(final Object key) {
    return this.execute(new RedisCallback() {
        public Object doWithRedis(Jedis jedis) {
            return SerializeUtil.unserialize(jedis.hget(RedisCache.this.id.toString().getBytes(), key.toString().getBytes()));
        }
    });
}

可以看出来,MyBatis-RedisCache 采用的是 redis 的 hash​ 结构来存储数据,把 Cache 的 id​ 作为 hash 的 key​(Cache 的 id 在 Mapper 中是 namspace),缓存和读取之前通过 SerializeUtil 进行 序列化 或者 反序列化

文章更新历史

2024/06/11 同步文章到其他平台

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis-Plus和Redis可以通过以下步骤实现: 1. 添加依赖:在pom.xml文件中添加Spring Boot、MyBatis-Plus和Redis的依赖。 ```xml <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置数据源:在application.properties或application.yml中配置数据库连接信息。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 3. 配置MyBatis-Plus:创建一个配置类,使用@MapperScan注解指定Mapper接口的扫描路径。 ```java @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ``` 4. 创建实体类和Mapper接口:创建实体类和对应的Mapper接口,使用注解进行映射。 ```java @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; } ``` ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 添加Redis配置:在application.properties或application.yml中配置Redis连接信息。 ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 6. 编写业务逻辑:创建Service类,注入Mapper和RedisTemplate,并编写业务逻辑。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private RedisTemplate<String, Object> redisTemplate; @Override public User getUserById(Long id) { // 先从缓存中获取数据 String key = "user:" + id; User user = (User) redisTemplate.opsForValue().get(key); // 如果缓存中不存在,则从数据库中获取数据 if (user == null) { user = userMapper.selectById(id); // 将数据存入缓存 redisTemplate.opsForValue().set(key, user); } return user; } } ``` 这样,你就成功地将Spring Boot、MyBatis-Plus和Redis进行了整合。通过MyBatis-Plus进行数据库操作,并通过Redis进行缓存,提高系统性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值