Spring缓存注解@Cacheable的使用

背景

我们在开发后台项目的时候,经常需要一些借助缓存缓存减少数据库的压力,但又不想引入redis组件,仅仅想使用本地缓存处理经常调用的方法,这里我们使用spring注解@Cacheable 来替代我们常用的Google cache,注解的方式使用起来要更加的便捷。

Maven引入


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
    <version>2.3.5.RELEASEversion>
dependency>

<dependency>
    <groupId>com.github.ben-manes.caffeinegroupId>
    <artifactId>caffeineartifactId>
    <version>2.3.5version>
dependency>

开启注解

启动类添加@EnableScheduling 注解,开启缓存注解

@Slf4j
@EnableScheduling   // 开启基于注解的缓存
@SpringBootApplication
@MapperScan("io.xx.xx.mapper")
public class MainApplication {

    public static void main(String[] args) {
        Environment env = new SpringApplication(MainApplication.class).run(args).getEnvironment();
    }

}

新增缓存配置

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * 缓存配置
 * 给定方法进行缓存 @Cacheable("xxxx")
 */
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
        		//配置缓存失效策略
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .maximumSize(5000);
        cacheManager.setCaffeine(caffeine);
        return cacheManager;
    }
}

使用方式

在需要使用的方法或类上直接使用注解@Cacheable(“xxx”) 或者 @Cacheable(value=“xxx”)

  • 作用在类上:表示当前类的所有方法均加入到缓存中
  • 作用在方法上:仅当前方法加入到缓存中
@Repository
public class UserDao {

   @Resource
   private UserMapper userMapper;

   @Cacheable("userByPhone")
   public UserPO selectUserByPhone(String phone) {
       QueryWrapper<CategoryDictPO> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("phone", phone);
       return userMapper.selectOne(queryWrapper);
   }

下面介绍一下 @Cacheable 这个注解常用的几个属性:

  • cacheNames/value :缓存组件的名字
  • key :缓存数据时使用的 key,可以用它来指定。默认是使用方法参数的值
  • keyGenerator :key 的生成器。 key 和 keyGenerator 二选一使用
  • cacheManager :可以用来指定从哪个缓存管理器里面获取缓存
  • condition :指定符合条件的情况下才缓存
  • unless :否定缓存。当 unless 指定的条件为 true ,方法的返回值就不会被缓存,如果对结果判断,可以通过 #result 获取方法结果,如:结果为空则不缓存,unless="#result == null"
  • sync :是否使用异步模式

你可能感兴趣的:(spring,spring,缓存,java)