Spring Boot 本机缓存:如何按单个键/元素过期/删除缓存数据

Ana*_*ika 6 caching spring-boot spring-cache

我们非常频繁地调用身份联合服务来获取用户令牌,并且几乎在身份服务上运行负载测试。

一个潜在的解决方案是在现有应用程序中缓存用户令牌,但是使用本机 spring-cache,我们可以使单个缓存条目过期吗?

通过下面的示例,我能够清除缓存,删除所有条目,但是我试图使单个条目过期。

@Service
@CacheConfig(cacheNames =  {"userTokens"})
public class UserTokenManager {

    static HashMap<String, String> userTokens = new HashMap<>();

    @Cacheable
    public String getUserToken(String userName){
        String userToken = userTokens.get(userName);
        if(userToken == null){
            // call Identity service to acquire tokens
            System.out.println("Adding UserName:" + userName + " Token:" + userToken);
            userTokens.put(userName, userToken);
        }
        return userToken;
    }

    @CacheEvict(allEntries = true, cacheNames = { "userTokens"})
    @Scheduled(fixedDelay = 3600000)
    public void removeUserTokens() {
        System.out.println("##############CACHE CLEANING##############, " +
            "Next Cleanup scheduled at : " + new Date(System.currentTimeMillis()+ 3600000));
        userTokens.clear();
    }
}
Run Code Online (Sandbox Code Playgroud)

Spring-boot 应用类如下:

@SpringBootApplication
@EnableCaching
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 19

您可以通过使用@CacheEvict获取缓存键的方法来使单个缓存条目过期。此外,通过使用 Spring 的缓存和@Cacheable,不需要 HashMap 代码(因为那实际上只是一个二级缓存)。

简单缓存

@Service
@CacheConfig(cacheNames = {"userTokens"})
public class UserTokenManager {

    private static Logger log = LoggerFactory.getLogger(UserTokenManager.class);

    @Cacheable(cacheNames = {"userTokens"})
    public String getUserToken(String userName) {
        log.info("Fetching user token for: {}", userName);
        String token = ""; //replace with call for token
        return token;
    }

    @CacheEvict(cacheNames = {"userTokens"})
    public void evictUserToken(String userName) {
        log.info("Evicting user token for: {}", userName);
    }

    @CacheEvict(cacheNames = {"userTokens"}, allEntries = true)
    public void evictAll() {
        log.info("Evicting all user tokens");
    }
}
Run Code Online (Sandbox Code Playgroud)

例如:

  1. getUserToken("Joe") -> no cache, calls API
  2. getUserToken("Alice") -> no cache, calls API
  3. getUserToken("Joe") -> cached
  4. evictUserToken("Joe") -> evicts cache for user "Joe"
  5. getUserToken("Joe") -> no cache, calls API
  6. getUserToken("Alice") -> cached (as it has not been evicted)
  7. evictAll() -> evicts all cache
  8. getUserToken("Joe") -> no cache, calls API
  9. getUserToken("Alice") -> no cache, calls API

基于 TTL 的缓存

如果您希望您的令牌被缓存一段时间,CacheManager除了本机 Spring 之外,您还需要另一个。有多种缓存选项可与 Spring 的@Cacheable. 我将给出一个使用 Caffeine 的示例,Caffeine 是一个用于 Java 8 的高性能缓存库。例如,如果您知道要缓存一个令牌 30 分钟,您可能会想要采用这条路线。

首先,将以下依赖项添加到您的build.gradle(或者,如果使用 Maven,请翻译以下内容并将其放入您的pom.xml)。请注意,您需要使用最新版本,或者与您当前的 Spring Boot 版本匹配的版本。

compile 'org.springframework.boot:spring-boot-starter-cache:2.1.4'
compile 'com.github.ben-manes.caffeine:caffeine:2.7.0'
Run Code Online (Sandbox Code Playgroud)

添加这两个依赖项后,您所要做的就是caffeineapplication.properties文件中配置规范:

spring.cache.cache-names=userTokens
spring.cache.caffeine.spec=expireAfterWrite=30m
Run Code Online (Sandbox Code Playgroud)

更改expireAfterWrite=30m为您希望代币生存的任何值。例如,如果您想要 400 秒,则可以将其更改为expireAfterWrite=400s.

有用的链接:


Mr.*_*mes 6

Spring Cache Abstraction 是一个抽象而不是一个实现,因此它根本不支持显式设置 TTL,因为这是一个特定于实现的功能。例如,如果您的缓存由 支持ConcurrentHashMap,则它不能开箱即用地支持 TTL。

在您的情况下,您有 2 个选择。如果您需要的是本地缓存(即每个微服务实例管理自己的缓存),您可以将 Spring Cache Abstraction 替换为由 Spring Boot 提供和管理的官方依赖项Caffeine。只需要声明而不提及版本。

<dependency>
  <groupId>com.github.ben-manes.caffeine</groupId>
  <artifactId>caffeine</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建缓存的实例,如下所示。您放入缓存中的每个令牌都将根据您的配置自动删除。

@Service
public class UserTokenManager {
    private static Cache<String, String> tokenCache;   

    @Autowired
    private UserTokenManager (@Value("${token.cache.time-to-live-in-seconds}") int timeToLiveInSeconds) {
        tokenCache = Caffeine.newBuilder()
                             .expireAfterWrite(timeToLiveInSeconds, TimeUnit.SECONDS)
                             // Optional listener for removal event
                             .removalListener((userName, tokenString, cause) -> System.out.println("TOKEN WAS REMOVED FOR USER: " + userName))
                             .build();
    }

    public String getUserToken(String userName){
        // If cached, return; otherwise create, cache and return
        // Guaranteed to be atomic (i.e. applied at most once per key)
        return tokenCache.get(userName, userName -> this.createToken(userName));
    }

    private String createToken(String userName) {
        // call Identity service to acquire tokens
    }
}
Run Code Online (Sandbox Code Playgroud)

同样,这是一个本地缓存,这意味着每个微服务将管理自己的一组令牌。因此,如果您有 5 个运行相同微服务的实例,则同一个用户可能有 5 个令牌位于所有 5 个缓存中,具体取决于哪些实例处理了他的请求。

另一方面,如果需要分布式缓存(即多个微服务实例共享同一个集中缓存),则需要查看EHCacheHazelcast。在这种情况下,您可以继续使用 Spring Cache Abstraction 并通过CacheManager从这些库(例如HazelcastCacheManager)中声明 a来选择这些库之一作为您的实现。

然后,您可以查看相应的文档以进一步配置您选择CacheManager的特定缓存(例如您的tokenCache)的TTL 。我在下面为 Hazelcast 提供了一个简单的配置作为示例。

@Configuration
public class DistributedCacheConfiguration {
    @Bean
    public HazelcastInstance hazelcastInstance(@Value("${token.cache.time-to-live-in-seconds}") int timeToLiveInSeconds) {
        Config config = new Config();                  
        config.setInstanceName("hazelcastInstance");

        MapConfig mapConfig = config.getMapConfig("tokenCache");
        mapConfig.setTimeToLiveSeconds(timeToLiveInSeconds);

        return Hazelcast.newHazelcastInstance(config);
    }

    @Bean
    public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
        return new HazelcastCacheManager(hazelcastInstance);
    }
}
Run Code Online (Sandbox Code Playgroud)