spring boot+redis+mybatis搭建,亲测可行

创建项目就不介绍了,创建时需要勾选Redis选项

1.引入redis依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4

2.在application.properties配置文件中配置redis

#redis配置
# redis数据库索引(默认为0)
spring.redis.database= 0
# redis服务器地址(默认为localhost)
spring.redis.host= 127.0.0.1
# redis端口(默认为6379)
spring.redis.port= 6379
# redis访问密码(默认为空)
spring.redis.password=
# redis连接超时时间(单位为毫秒)
spring.redis.timeout= 0
# redis连接池配置

# 最大可用连接数(默认为8,负数表示无限)
spring.redis.pool.max-active= 100
# 最大空闲连接数(默认为8,负数表示无限)
spring.redis.pool.max-idle= 20
# 最小空闲连接数(默认为0,该值只有为正数才有作用)
spring.redis.pool.min-idle= 8
# 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限)
spring.redis.pool.max-wait= -1
并开启mybatis的二级缓存
#开启MyBatis的二级缓存
mybatis.configuration.cache-enabled=true


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.创建cache包,然后创建两个类,一个ApplicationContextHolder实现ApplicationContextAware接口,具体内容如下

package com.book.demo.cache;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        applicationContext = ctx;
    }

    /**
     * Get application context from everywhere
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Get bean by class
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * Get bean by class name
     *
     * @param name
     * @param <T>
     * @return
     */

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
}

4.创建RedisCache类实现Cache接口,具体内容如下:

package com.book.demo.cache;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

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 logger = LoggerFactory.getLogger(RedisCache.class);

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final String id; // cache instance id
    private RedisTemplate redisTemplate;

    private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间

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

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

    /**
     * Put query result to redis
     *
     * @param key
     * @param value
     */
    @Override
    public void putObject(Object key, Object value) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            ValueOperations opsForValue = redisTemplate.opsForValue();
            opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
            logger.debug("Put query result to redis");
        }
        catch (Throwable t) {
            logger.error("Redis put failed", t);
        }
    }

    /**
     * Get cached query result from redis
     *
     * @param key
     * @return
     */
    @Override
    public Object getObject(Object key) {
        try {

            RedisTemplate redisTemplate = getRedisTemplate();
            ValueOperations opsForValue = redisTemplate.opsForValue();
            logger.debug("Get cached query result from redis");
            //System.out.println("****"+opsForValue.get(key).toString());
            return opsForValue.get(key);
        }
        catch (Throwable t) {
            logger.error("Redis get failed, fail over to db", t);
            return null;
        }
    }

    /**
     * Remove cached query result from redis
     *
     * @param key
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object removeObject(Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            redisTemplate.delete(key);
            logger.debug("Remove cached query result from redis");
        }
        catch (Throwable t) {
            logger.error("Redis remove failed", t);
        }
        return null;
    }

    /**
     * Clears this cache instance
     */
    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        logger.debug("Clear all the cached query result from redis");
    }

    /**
     * This method is not used
     *
     * @return
     */
    @Override
    public int getSize() {
        return 0;
    }

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

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


5.实体类中实现Serializable接口

public class Book implements Serializable{

    private static  final long serialVesionUID=-2566441764189220519L;


 6.配置***mapper.xml文件
 
 
<cache type="com.book.demo.cache.RedisCache"></cache>

到此完成了对redis的配置
  现在我们还需要安装redis,redis分为集群的和单机的,我们这里选择安装单机的
1、下载redis地址:https://github.com/dmajkic/redis/downloads   
     直接解压选择32或者64位,重命名即可
  2、启动服务:
     cmd进入根目录执行redis-server.exe redis.conf   //启动正常能看到redis操作的日志
     
cmd窗口不要关,现在可以运行我们的项目,redis就成功集成了。(此处关于redis的安装比较简略,但是可行的,读者可自行查阅redis安装的一些资料)


猜你喜欢

转载自blog.csdn.net/make__it/article/details/79288527