天天看点

SpringBoot整合redis之环境搭建(搭建分布式缓存)

目录

1、引入 redis

1.1 引入相关依赖

1.2 配置 redis 连接

1.3 编写 redis 的配置类

2、使用 redis 缓存

2.1 自定义 RedisCache(redis的缓存实现)

2.2 修改缓存类型

3、测试

说明:本章是继 SpringBoot整合redis之环境搭建(Mybatis 缓存)https://blog.csdn.net/u010559460/article/details/109388128 这之后进行编写的。将原来使用的 mybatis 缓存(本地缓存)改造成 redis 缓存(分布式缓存)

1、引入 redis

1.1 引入相关依赖

<!--引入依赖 spring data redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- 阿里JSON解析器 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <!-- pool 对象池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
           

1.2 配置 redis 连接

编辑 application.yml  文件, 新增 redis 的配置信息

spring:
    # redis 配置
  redis:
    # 地址
    host: # 填写自己的 ip
    # 端口,默认为6379
    port: 6379
    # 密码
    password:  #填写自己的密码
    # 连接超时时间
    timeout: 10s
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms
           

1.3 编写 redis 的配置类

redis 配置类主要是 往容器中注入 redisTemplate 的bean 对象

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean("redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

}
           

此处用到 FastJson2JsonRedisSerializer 自定义的 redis序列号类, 代码如下:

/**
 * Redis使用FastJson序列化
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    @SuppressWarnings("unused")
    private ObjectMapper objectMapper = new ObjectMapper();

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);
    }

    public void setObjectMapper(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }

    protected JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}
           

2、使用 redis 缓存

2.1 自定义 RedisCache(redis的缓存实现)

Mybatis 默认使用 org.apache.ibatis.cache.impl.PerpetualCache 完成本地缓存,我们可以参考这个类来编写

/**
 * 1. 自定义 RedisCache 实现分布式缓存
 */
public class RedisCache implements Cache {
    // 2. 定义String 类型 id, id的值 就是当前放入缓存Mapper的namespaces的值
    private final String id;
    // 3. 构造方法,初始化 id的值
    public RedisCache(String id) {
        this.id = id;
    }
    // 4. cache 唯一标识
    @Override
    public String getId() {
        return id;
    }

    /**
     * 往 缓存中放置数据
     * @param key
     * @param value
     */
    @Override
    public void putObject(Object key, Object value) {
        // 使用 redisHash 类型作为缓存的存储模型  key hashKey value
        getRedisTemplate().opsForHash().put(id.toString(), key.toString(), value);
    }

    /**
     * 从 缓存中获取数据
     * @param key
     * @return
     */
    @Override
    public Object getObject(Object key) {
        return getRedisTemplate().opsForHash().get(id.toString(), key.toString());
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }

    /**
     * 清空缓存
     */
    @Override
    public void clear() {
        getRedisTemplate().delete(id.toString());
    }

    /**
     * 计算 缓存的数量
     * @return
     */
    @Override
    public int getSize() {
        return getRedisTemplate().opsForHash().size(id.toString()).intValue();
    }

    /**
     * 通过 ApplicationContext工具类, 获取 redisTemplate
     */
    private RedisTemplate getRedisTemplate(){
        return (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
    }
}
           

此处用到 ApplicationContextUtils 自定义的工具类, 补充说明,平时我们在编写Controller或Service层代码时,需要从Spring容器中获取对象,那只需要 @Autowire 或 @Resource 注解就可以。但

如果要创建的这个对象不是有 Spring 管理的,那就不能直接使用  @Autowire 或 @Resource,而是要实现 ApplicationContextAware,然后往里面传递 ApplicationContext 对象(容器对象),调用ApplicationContext 对象的 getBean 方法获取bean。 考虑到别的地方也可能会有获取bean的操作,因此封装 ApplicationContextUtils 类来获取bean 对象

ApplicationContext 类:

@Component
public class ApplicationContextUtils implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

    // 将创建好的工厂 以参数的形式传递给这个类
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 提供 获取bean 对象的方法
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
}
           

2.2 修改缓存类型

在 UserDaoMapper.xml 文件中,添加

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lcy.dao.UserDao">
    <!--开启二级缓存-->
    <cache type="com.lcy.cache.RedisCache"/>
。。。。。
           

这样的话,当我们进行查询操作的时候,Mybatis就会使用我们自定义 RedisCache 而不是使用它自带的 PerpetualCache 缓存

3、测试

测试方法这里就不重复了,都是https://blog.csdn.net/u010559460/article/details/109388128 这一章里边的。

 

 

 

 

 

 

 

 

 

继续阅读