spring boot:redis缓存、redis_session配置备忘

  • 按照下方步骤可轻松完成redis缓存的配置过程

应用场景:在一些不常改动,但又经常读取的业务数据进行缓存处理,减少服务器处理请求时间,减小服务器压力。

1.在pom.xml文件中添加依赖

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

2.在application.yml文件中加入redis链接参数

spring:
    redis:
        host: 192.168.2.190
        port: 6379
        password: replace of your password

3.编写redis序列化类

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * redis序列化对象
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {
    private Converter<Object, byte[]> serializer = new SerializingConverter();
    private Converter<byte[], Object> deserializer = new DeserializingConverter();
    static final byte[] EMPTY_ARRAY = new byte[0];

    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return deserializer.convert(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
        }
    }

    public byte[] serialize(Object object) {
        if (object == null) {
            return EMPTY_ARRAY;
        }
        try {
            return serializer.convert(object);
        } catch (Exception ex) {
            return EMPTY_ARRAY;
        }
    }

    private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }
}

4.编写redis配置类

import java.lang.reflect.Method;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * redis 配置
 */
@Configuration
@EnableCaching  // 启用缓存
@EnableRedisHttpSession     //启用redis session
public class RedisConfig {
    
    private static final String NULL = "NULL";

    @Bean
      public KeyGenerator wiselyKeyGenerator(){
          return new KeyGenerator() {
              @Override
              public Object generate(Object target, Method method, Object... params) {
                  StringBuilder sb = new StringBuilder();
                  sb.append(target.getClass().getName());
                  sb.append(method.getName());
                  for (Object obj : params) {
                      sb.append(obj==null?NULL:obj.toString());
                  }
                  return sb.toString();
              }
          };
      }

    @Bean
    public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(1800);
        return cacheManager;
    }
    
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
}

在RedisConfig配置类名上标注@EnableCaching注解,启用redis缓存;@EnableRedisHttpSession 启用redis session

5.测试缓存

使用spring框架的缓存注解@Cacheable、@CacheEvict进行测试,详细的注解参数,可百度查看更多说明

  • [x] 缓存查询结果
@Cacheable(value = MENU_CACHE, keyGenerator = "wiselyKeyGenerator")
    @Override
    public List<SysBgMenu> getMenuList(SysUser user) {
        // 1、查询父级节点
        // 2、递归查询子集节点(此处只处理了2级显示,按后期需求再定是否只是多级菜单)
        String userId = user == null ? null : user.getId();
        List<SysBgMenu> firstLevelMenus = sysBgMenuMapper.selectFirstLevelMenu(userId);
        for (SysBgMenu menu : firstLevelMenus) {
            menu.setSubMenus(sysBgMenuMapper.selectNextLevelMenu(userId, menu.getId()));
        }
        return firstLevelMenus;
    }
  • [x] 当记录修改时,清除缓存
    @CacheEvict(value = MENU_CACHE, allEntries = true)
    @Override
    public void save(SysBgMenu param) {
        super.save(param);
    }

==在测试时,提前编译一下项目,预防程序和代码不同步问题,白白浪费调试时间==

    原文作者:佚可
    原文地址: https://www.jianshu.com/p/e662ea022849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞