前言

笔者在毕业设计中使用了Mybatis作为ORM框架,想要使用Redis作为缓存来提升数据库性能。本文简单的介绍了如何使用Redis作为Mybatis的二级缓存。

配置Redis

添加Redis依赖

首先在maven中添加Redis的依赖。

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

配置Redis连接

在配置文件中添加Redis连接的相关配置。(这里笔者使用的是yaml格式的配置文件)

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 12345678

增加Redis的配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

配置Mybatis

开启Mybatis缓存

在配置文件中开启Mybatis缓存。(这里笔者使用的是yaml格式的配置文件)

mybatis:
  configuration:
    cache-enabled: true

创建RedisCache类,实现Mybatis的Cache接口

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {

    private static final Logger LOG = LoggerFactory.getLogger(RedisCache.class);
    private static final int DEFAULT_REDIS_EXPIRE = 10;
    private static RedisTemplate<String, Object> redisTemplate = null;
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
    private String id = null;
    public RedisCache(final String id) {
        if (null == id) {
            throw new IllegalArgumentException("MybatisRedisCache Instance Require An Id...");
        }
        LOG.info("MybatisRedisCache: " + id);
        this.id = id;
    }
    @Override
    public String getId() {
        return this.id;
    }
    @Override
    public void putObject(Object key, Object value) {
        if (null != value) {
            LOG.info("putObject key: " + key.toString());
            redisTemplate.opsForValue().set(key.toString(), value, DEFAULT_REDIS_EXPIRE, TimeUnit.MINUTES);
        }
    }
    @Override
    public Object getObject(Object key) {
        try {
            if (null != key) {
                LOG.info("getObject key: " + key.toString());
                return redisTemplate.opsForValue().get(key.toString());
            }
        } catch (Exception e) {
            LOG.error("getFromRedis: " + key.toString() + " failed!");
        }
        LOG.info("getObject null...");
        return null;
    }
    @Override
    public Object removeObject(Object keyObject) {
        if (null != keyObject) {
            redisTemplate.delete(keyObject.toString());
        }
        return null;
    }
    @Override
    public void clear() {
        LOG.info("clear......");
        try {
            Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
            LOG.info("keys size: " + keys.size());
            for (String key : keys) {
                LOG.info("key : " + key);
            }
            if (!CollectionUtils.isEmpty(keys)) {
                redisTemplate.delete(keys);
            }
        } catch (Exception e) {
            LOG.error("clear failed!", e);
        }
    }
    @Override
    public int getSize() {
        Long size = (Long) redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize();
            }
        });
        LOG.info("getSize: " + size.intValue());
        return size.intValue();
    }
    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
    public static void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisCache.redisTemplate = redisTemplate;
    }
}

注入redisTemplate

创建一个配置类来注入redisTemplate。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class WiredRedisTemplate {
    @Autowired
    @Qualifier("redisTemplate")
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisCache.setRedisTemplate(redisTemplate);
    }
}

在Mapper文件中配置二级缓存

在需要开启缓存的Mapper中添加如下注解即可。

@CacheNamespace(implementation= RedisCache.class)

参考文章

Spring Boot之基于Redis实现MyBatis查询缓存解决方案

版权声明: 本博客所有文章除特别声明外,均采用署名-非商业性使用-相同方式共享 4.0 国际CC BY-NC-SA 4.0 )许可协议。转载请注明出处!
最后修改:2021 年 02 月 24 日 12 : 14 AM
如果觉得我的文章对你有用,请随意赞赏