首先导入依赖
<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("缓存已存在");
}