SpringBoot教程(五)——集成本地缓存CaffeineCache

1.引入依赖

2.创建配置类

3.启动类中加入 @EnableCaching 注解 开启缓存

4.测试注解方式

1.引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

2.创建配置类

@Configuration
public class CacheConfig {

    @Bean("caffeineCacheManager")
    public CacheManager caffeineCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        /*
        Caffeine配置说明:
            initialCapacity=[integer]: 初始的缓存空间大小
            maximumSize=[long]: 缓存的最大条数
            maximumWeight=[long]: 缓存的最大权重
            expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期
            expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期
            refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
            weakKeys: 打开key的弱引用
            weakValues:打开value的弱引用
            softValues:打开value的软引用
            recordStats:开发统计功能
        注意:
            expireAfterWrite和expireAfterAccess同事存在时,以expireAfterWrite为准。
            maximumSize和maximumWeight不可以同时使用
            weakValues和softValues不可以同时使用
        */
        Caffeine<Object, Object> caffeine =
                Caffeine.newBuilder()
                        .initialCapacity(100)
                        .maximumSize(100)
                        .expireAfterWrite(600, TimeUnit.SECONDS);
        cacheManager.setCaffeine(caffeine);
        cacheManager.setCacheNames(Collections.singletonList(Constants.LOCAL_CACHE_NAME));//可设置多个缓存名称
        return cacheManager;
    }

}

3.启动类中加入 @EnableCaching 注解 开启缓存

@SpringBootApplication
@EnableCaching
public class SpringBootCacheApplication {

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

}

4.测试注解方式

@Service
@Slf4j
public class TestService {

    @Cacheable(value = Constants.LOCAL_CACHE_NAME, key = Constants.LOCAL_KEY + "+#key")
    public Object get(String key) {
        Object o = new Object();
        // do something
        return o;
    }


    @CachePut(value = Constants.LOCAL_CACHE_NAME, key = Constants.LOCAL_KEY + "+#key")
    public Object set(String key, Object value) {
        // do something
        return value;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值