Springboot+redis+@Cacheable实现缓存

1.先导入redis与cache的依赖

        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.springframework.boot
            spring-boot-starter-cache
        

2.在启动类添加注解@EnableCaching 开启缓存

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.mall.model.dao")
@EnableCaching
public class ImoocMallApplication {

    public static void main(String[] args) {
        SpringApplication.run(ImoocMallApplication.class, args);
    }

}

3.设置缓存配置,设置超时时间等

package com.imooc.mall.config.cache;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;

/**
 * @author zwj
 * @Description: 缓存的配置类
 * @date 2022/10/30 3:12 上午
 */
@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter, cacheConfiguration);
        return redisCacheManager;
    }
}

4.在需要设置缓存的业务层中,添加注解@Cacheable,value属性为redis种缓存的key值

    @Override
    @Cacheable(value = "listCategoryForCustomer")
    public List listCategoryForCustomer(Integer parentId) {
        List categoryVOS = new ArrayList<>();
        recursivelyFindCategories(categoryVOS, parentId);
        return categoryVOS;
    }

你可能感兴趣的:(工作学习笔记,spring,boot,缓存,redis)