SpringBoot+Caffeine 本地缓存

maven配置

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.8.8</version>
</dependency>

yml配置

spring:
  cache:
    type: caffeine
    cache-names:
      - interfaceCache
    caffeine:
      spec: initialCapacity=100,maximumSize=2000,expireAfterWrite=1h
maximumSize
配置缓存的最大容量,当快要达到容量上限的时候,缓存管理器会根据一定的策略将部分缓存项移除。
expireAfterAccess
配置缓存项的过期机制,如代码所示当缓存项被访问后一小时将会过期,从而被移除。   (秒级配置:10s)   

代码层

1、启动类Application添加@EnableCaching

@EnableCaching
@SpringBootApplication
public class Application {
    
    }

2、无参实现

    @Cacheable(value = "interfaceCache", key = Constants.PREFIX_OF_CACHE_KEY1, unless = "#result == null || #result.size()==0")
    public String getA() {
    
    }

3、有参实现

    @Cacheable(value = "interfaceCache", key = "T(com.a.utils.Constants).PREFIX_OF_CACHE_KEY2.concat('-').concat(#p1).concat('-').concat(#p2)", unless = "#result == null || #result.size()==0")
    public String  getA(String p1, Integer p2) {
    
    }

猜你喜欢

转载自blog.csdn.net/u013947963/article/details/111595655