springboot使用caffeine做本地缓存

首先导入依赖

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

然后写配置类

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author qingshi
 * @date 2022/12/16 17:07
 * info:caffeine缓存
 */
@Configuration
public class CacheConfig {
    @Bean
    public Cache<String, Object> caffeineCache() {//想做多个不同的缓存,只需要复制多个这个bean即可
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(5, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .build();
    }
}

然后在service注入bean

@Autowired
Cache<String,Object> cache;

然后使用

Object cacheIfPresent = cache.getIfPresent(user_id);
if (ObjectUtils.isEmpty(cacheIfPresent)){//如果不存在缓存
  cache.put(user_id,messages);//则放入缓存
 }else {
   System.out.println("缓存已存在");
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值