欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【Redis】SpringBoot+MyBatis集成Redis二级缓存

程序员文章站 2022-03-25 13:01:22
在pom文件中增加如下依赖 org.springframework.boot spring-boot-starter-data-redis&l...

在pom文件中增加如下依赖

<!--Spring Redis RedisAutoConfiguration-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>3.2.0</version>
</dependency>

spring配置文件application.properties中新增如下配置

#配置redis连接
#因为在我的电脑的hosts文件中已经配置了与CentOS的主机映射关系,在此主机地址可以直接使用CentOS代替
spring.redis.host=CentOS
#redis端口号
spring.redis.port=6379
#连接时间
spring.redis.timeout=5s
#redis连接池参数
spring.redis.lettuce.shutdown-timeout=100ms
#连接池最大连接数(使用负值表示没有限制)默认为8
spring.redis.lettuce.pool.max-active=10
#连接池中最大的空闲连接,默认为8
spring.redis.lettuce.pool.max-idle=8
#连接池最大阻塞等待时间(使用负值表示没有限制)默认-1
spring.redis.lettuce.pool.max-wait=5ms
#连接池中最小空闲连接 默认为0
spring.redis.lettuce.pool.min-idle=1

新增以下类

ApplicationContextHolder.java

/**
* 该接口为标记接口,Spring工厂在初始化时,会自动注入applicationContext
*/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContex;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // this.applicationContex = applicationContext;
        applicationContex = applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContex.getBean(beanName);
    }
}

UserDefineRedisCache.java

/**
 * 自定义redis缓存
 */
public class UserDefineRedisCache implements Cache {
    private Logger logger = LoggerFactory.getLogger(UserDefineRedisCache.class);

    private String id; //存储namespace
    private long timeout = 300; //超时时间
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private RedisTemplate redisTemplate; //(RedisTemplate) ApplicationContextHolder.getBean("redisTemplate");

    public UserDefineRedisCache(String id) {
        this.id = id;
    }

    private RedisTemplate getRedisTemplate() {
        return (RedisTemplate) ApplicationContextHolder.getBean("redisTemplate");
    }

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

    @Override
    public void putObject(Object key, Object value) {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("将查询结果存储到cache.key:" + key + ",value:" + value);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, value, timeout, TimeUnit.SECONDS);
    }

    @Override
    public Object getObject(Object key) {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("从缓存中读取结果.key:" + key);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        return opsForValue.get(key);
    }

    @Override
    public Object removeObject(Object key) {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("从缓存中清除.key:" + key);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        Object value = opsForValue.get(key);
        redisTemplate.delete(key);
        return value;
    }

    @Override
    public void clear() {
        if (redisTemplate == null) {
            redisTemplate = getRedisTemplate();
        }
        logger.debug("从缓存中清除缓存区所有数据");
        redisTemplate.execute((RedisConnection connection) -> {
            connection.flushAll();
            return null;
        });
    }

    @Override
    public int getSize() {
        return 0;
    }

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

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }
}

在SpringBoot启动类中加入如下方法

//配置RedisBean
@Bean
public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory connectionFactory) throws UnknownHostException {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(connectionFactory);
    //设置Key、value的序列化
    redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    return redisTemplate;
}

在MyBatis配置文件中开启mybatis二级缓存

<!--
	二级缓存
	type指向我们所定义的redis缓存类
-->
<cache type="com.dora.cache.UserDefineRedisCache">
    <!--设置超时时间-->
    <property name="timeout" value="150"/>
</cache>

本文地址:https://blog.csdn.net/qq_44664231/article/details/109804496