SpringBoot Redis 2.0.x

  • redis的安装
    在笔者之前的文章中有介绍redis的安装,不会的可以去看 笔者之前写的文章redis安装
  • 完成安装后如果不熟悉redis的操作,redis官方文档也有基本操作指南,redis基本操作,如果觉得没问题了就可以开始对redis的整合
  1. maven安装依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

redis自动会吧cache的依赖带过来,所有不用配置,如图

  1. 启动类增加@EnableCaching 注解
@SpringBootApplication
@MapperScan("com.tanoak.mapper")
@EnableCaching
public class BootRedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootRedisApplication.class, args);
    }
}
  1. service层增加@Cacheable 注解
@Override
    @Cacheable(cacheNames= "tea")
    public Teacher getTeaById(Integer id) {
        logger.info("进行查询实体 ID为"+id);
        return teacherMapper.getTeaById(id) ;
    }
  1. controller 查询
@GetMapping("/tea/{id}")
public Teacher getTea(@PathVariable("id")Integer id){
        return  teacherService.getTeaById(id) ;
    }

RedisCacheManager 配置

在SpringBoot2.x中,移除了1.x中的配置,因此要配置Json序列化与1.x的差别很大,看代码


@Configuration
@EnableCaching
public class MyRedisConfig extends CachingConfigurerSupport {

    /*
    *自定义键生成策略
    */
    @Bean
    public KeyGenerator KeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }


    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        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);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
                //设置默认超过期时间是30秒
        ).entryTtl(Duration.ofMinutes(30));

        return redisCacheConfiguration;
    }

}


没有打印sql,说明缓存成功,与redis集成就完成了

猜你喜欢

转载自www.cnblogs.com/tanoak/p/10545247.html