溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Spring Boot Cache使用方法整合代碼實(shí)例

發(fā)布時(shí)間:2020-10-14 21:15:49 來(lái)源:腳本之家 閱讀:254 作者:Kancy 欄目:編程語(yǔ)言

參考:

Spring Cache擴(kuò)展功能實(shí)現(xiàn)

項(xiàng)目地址

使用本地Caffeine緩存

引入依賴(lài)包

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

自定義Caffeine配置

CachingConfig.java

package com.vcredit.vmp.checkcenter.config;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.vcredit.vmp.checkcenter.common.properties.CaffeineCacheProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.Duration;
import java.util.*;
/**
 * 緩存配置
 * @author kancy
 */
@Configuration
@EnableCaching
public class CachingConfig {

  @Autowired
  CaffeineCacheProperties caffeineCacheProperties;

  /**
   * 創(chuàng)建基于Caffeine的Cache Manager
   * @return
   */
  @Bean
  @Primary
  @ConditionalOnProperty(prefix = "system.cache.caffeine" , name = "enabled", havingValue = "true")
  public CacheManager caffeineCacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    Map<String, CaffeineCache> cacheMap = new HashMap();

    // 設(shè)置全局配置的本地緩存
    List<String> globalCacheNames = caffeineCacheProperties.getCacheName();
    if(globalCacheNames !=null && !globalCacheNames.isEmpty()){
      addCacheObject(cacheMap, globalCacheNames, caffeineCacheProperties.getExpireAfterWrite(),
          caffeineCacheProperties.getExpireAfterAccess(), caffeineCacheProperties.getMaximumSize());
    }

    // 設(shè)置自定義屬性緩存, 可以覆蓋全局緩存
    List<CaffeineCacheProperties.Config> configs = caffeineCacheProperties.getConfigs();
    if(configs != null && !configs.isEmpty()){
      for (CaffeineCacheProperties.Config config : configs) {
        List<String> cacheNames = config.getCacheName();
        if (cacheNames == null || cacheNames.isEmpty()){
          continue;
        }
        Duration expireAfterWrite = Optional.ofNullable(config.getExpireAfterWrite()).orElse(caffeineCacheProperties.getExpireAfterWrite());
        Duration expireAfterAccess = Optional.ofNullable(config.getExpireAfterAccess()).orElse(caffeineCacheProperties.getExpireAfterAccess());
        Long maximumSize = Optional.ofNullable(config.getMaximumSize()).orElse(caffeineCacheProperties.getMaximumSize());
        addCacheObject(cacheMap, cacheNames, expireAfterWrite, expireAfterAccess, maximumSize);
      }
    }
    // 加入到緩存管理器進(jìn)行管理
    cacheManager.setCaches(cacheMap.values());
    return cacheManager;
  }

  private void addCacheObject(Map<String, CaffeineCache> cacheMap, List<String> cacheNames, Duration expireAfterWrite, Duration expireAfterAccess, Long maximumSize) {
    for (String cacheName : cacheNames) {
      // spring.cache.caffeine: maximumSize=500,expireAfterAccess=10s,expireAfterWrite=15s
      Caffeine<Object, Object> recordStats = Caffeine.newBuilder().recordStats().maximumSize(maximumSize);
      if(expireAfterAccess != null) recordStats.expireAfterAccess(expireAfterAccess);
      if(expireAfterWrite != null) recordStats.expireAfterWrite(expireAfterWrite);
      Cache<Object, Object> cache = recordStats.build();
      CaffeineCache caffeineCache = new CaffeineCache(cacheName,cache);

      // 覆蓋添加
      cacheMap.put(cacheName, caffeineCache);
    }
  }
}

CaffeineCacheProperties.java

package com.vcredit.vmp.checkcenter.common.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.List;
/**
 * Caffeine本地緩存自定義配置
 * @author kancy
 */
@Getter
@Setter
@Configuration
@ConfigurationProperties("system.cache.caffeine")
@ConditionalOnProperty(prefix = "system.cache.caffeine" , name = "enabled", havingValue = "true")
public class CaffeineCacheProperties {
  private List<String> cacheName;
  private Duration expireAfterWrite;
  private Duration expireAfterAccess;
  private Long maximumSize = Long.valueOf(-1);
  private List<Config> configs;
  @Getter
  @Setter
  public static class Config {
    private List<String> cacheName;
    Duration expireAfterWrite;
    Duration expireAfterAccess;
    Long maximumSize;
  }
}

application.yml

system.cache.caffeine:
 enabled: true
 # 全局配置
 cacheName: cache1,cache2,cache3
 expireAfterWrite: 60s
 expireAfterAccess: 30s
 maximumSize: 500
 # 自定義配置,cacheName相同可覆蓋全局
 configs:
 - cacheName: checkApplyCache
  expireAfterAccess: 10s
 - cacheName: userQueryCache
  expireAfterAccess: 15s

使用緩存

@Cacheable(value = { "checkApplyCache" }, key="#req.md5")
public Result check(CheckReq req) {
  // your code...
  return Result.ok();
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI