Spring Boot 使用Caffeine缓存

Spring Boot 使用Caffeine缓存

Caffeine是Java8重写Guava缓存,取代Guava缓存。
Spring Cache相关注解基础请查看这篇文章

Caffeine官方的介绍

caffeine官网
Caffeine是基于Java8的高性能,接近完美的缓存库。

demo

pom.xml
引入spring-context-support

		<dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

或者spring-boot-starter-cache

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

Caffeine配置参数

属性说明
initalCapacity初始空间大小
maximumSize缓存最大条数
maximumWeight缓存的最大权重
expireAfterAccess最后一次写入或访问后经过固定时间过期
expireAfterWrite最后一次写入后经过固定时间过期
refreshAfterWrite创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
weakKeys打开key的弱引用
weakValues打开value的弱引用
softValues打开value的软引用
recordStats开发统计功能
  • 注意
    refreshAfterWrite 要实例 LoadingCache 否则报错
    java.lang.IllegalStateException: refreshAfterWrite requires a LoadingCache

application.yml

spring:
  cache:
    cache-names:
      - cache1
      - cache2
    type: caffeine
    caffeine:
      spec:
        maximumSize=500,expireAfterAccess=600s


yml文件中的配置也可以通过bean来配置

CacheConfig.java

package com.jsong.wiki.blog.config;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;


@Configuration
public class CacheConfig {

    @Bean("caffeineCacheManager")
    public CacheManager caffeineCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(10_1000)
                .expireAfterAccess(5, TimeUnit.SECONDS));
        return cacheManager;
    }

    /* 如果配置refreshAfterWrite要有这个bean,否则报错
    java.lang.IllegalStateException: refreshAfterWrite requires a LoadingCache*/
    @Bean
    public CacheLoader<Object, Object> cacheLoader() {
        CacheLoader<Object, Object> cacheLoader = new CacheLoader<Object, Object>() {
            @Nullable
            @Override
            public Object load(@NonNull Object key) throws Exception {
                return null;
            }
        };
        return cacheLoader;
    }

}


CacheService.java

package com.jsong.wiki.blog.service;

import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Component;

@EnableCaching
@CacheConfig(cacheNames = "caffeineCacheManager")
@Component
public class CacheService {

    @Cacheable(value = "cache1", key = "#root.target")
    public String getName() {
        System.out.println("cache1");
        return "cache1";
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot Caffeine 是一个用于集成 Spring BootCaffeine 缓存库的插件。Caffeine 是一个高性能的 Java 缓存库,它提供了内存缓存的功能,可以减少对数据库或其他外部资源的访问次数,从而提高应用程序的性能。 要在 Spring Boot使用 Caffeine,首先需要添加以下 Maven 依赖项: ```xml <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> ``` 接下来,在你的 Spring Boot 应用程序的配置类上添加 `@EnableCaching` 注解,以启用缓存功能。然后,在需要缓存的方法上添加 `@Cacheable` 注解,指定缓存的名称和缓存的键。 例如,假设你有一个 UserService 类,其中有一个需要进行缓存的方法 getUserById: ```java @Service public class UserService { @Cacheable("users") public User getUserById(Long id) { // 从数据库或其他外部资源获取用户信息 return userRepository.findById(id); } } ``` 在上面的例子中,使用了 `@Cacheable("users")` 注解来指定缓存的名称为 "users",并且根据传入的 id 参数进行缓存。当该方法被调用时,如果缓存中已经存在相应的键值对,则直接从缓存中获取结果,否则会执行方法体内的代码,并将结果存入缓存中。 另外,你还可以使用 `@CacheEvict` 注解来清除缓存中的数据,例如: ```java @CacheEvict("users") public void deleteUserById(Long id) { // 删除用户操作 } ``` 上述代码中的 `@CacheEvict("users")` 注解会在 deleteUserById 方法执行后清除名为 "users" 的缓存。 通过以上的配置和注解,你就可以在 Spring Boot 应用程序中使用 Caffeine 缓存来提高性能了。当然,还有其他更多的配置选项和注解可以使用,你可以根据自己的需求进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值