自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

SpringBoot 如何快速使用 Caffeine 緩存?

存儲 存儲軟件
引入 Caffeine 和 Spring Cache 依賴,使用 SpringCache 注解方法實現(xiàn)緩存。SpringCache幫我們封裝了Caffeine pom文件引入。

[[433190]]

引言

前面我們有學(xué)習(xí)Caffeine 《本地緩存性能之王Caffeine》,并且也提到SpringBoot默認(rèn)使用的本地緩存也是Caffeine啦,今天我們來看看Caffeine如何與SpringBoot集成的。

集成caffeine

caffeine與SpringBoot集成有兩種方式:

  • 一種是我們直接引入 Caffeine 依賴,然后使用 Caffeine 方法實現(xiàn)緩存。相當(dāng)于使用原生api
  • 引入 Caffeine 和 Spring Cache 依賴,使用 SpringCache 注解方法實現(xiàn)緩存。SpringCache幫我們封裝了Caffeine pom文件引入
  1. <dependency> 
  2.     <groupId>org.springframework.boot</groupId> 
  3.     <artifactId>spring-boot-starter-cache</artifactId> 
  4. </dependency> 
  5. <dependency> 
  6.     <groupId>com.github.ben-manes.caffeine</groupId> 
  7.     <artifactId>caffeine</artifactId> 
  8.     <version>2.6.0</version> 
  9. </dependency> 

第一種方式

首先配置一個Cache,通過構(gòu)造者模式構(gòu)建一個Cache對象,然后后續(xù)關(guān)于緩存的增刪查都是基于這個cache對象。

  1. @Configuration 
  2. public class CacheConfig { 
  3.     @Bean 
  4.     public Cache<String, Object> caffeineCache() { 
  5.         return Caffeine.newBuilder() 
  6.                 // 設(shè)置最后一次寫入或訪問后經(jīng)過固定時間過期 
  7.                 .expireAfterWrite(60, TimeUnit.SECONDS) 
  8.                 // 初始的緩存空間大小 
  9.                 .initialCapacity(100) 
  10.                 // 緩存的最大條數(shù) 
  11.                 .maximumSize(1000) 
  12.                 .build(); 
  13.     } 

第一種方式我們就一一不介紹了,基本上就是使用caffeineCache來根據(jù)你自己的業(yè)務(wù)來操作以下方法

這種方式使用的話是對代碼有侵入性的。

第二種方式

  • 需要在SpingBoot啟動類標(biāo)上EnableCaching注解,這個玩意跟很多框架都一樣,比如我們肴集成dubbo也需要標(biāo)上@EnableDubbole注解等。
  1. @SpringBootApplication 
  2.   @EnableCaching 
  3.   public class DemoApplication { 
  4.       public static void main(String[] args) { 
  5.           SpringApplication.run(DemoApplication.class, args); 
  6.       } 
  • 在application.yml配置我們的使用的緩存類型、過期時間、緩存策略等。
  1. spring: 
  2.   profiles: 
  3.     active: dev 
  4.   cache: 
  5.     type: CAFFEINE 
  6.     caffeine: 
  7.       spec: maximumSize=500,expireAfterAccess=600s 

如果我們不習(xí)慣使用這種方式的配置,當(dāng)然我們也可以使用JavaConfig的配置方式來代替配置文件。

  1. @Configuration 
  2. public class CacheConfig { 
  3.         @Bean 
  4.         public CacheManager cacheManager() { 
  5.             CaffeineCacheManager cacheManager = new CaffeineCacheManager(); 
  6.             cacheManager.setCaffeine(Caffeine.newBuilder() 
  7.                     // 設(shè)置最后一次寫入或訪問后經(jīng)過固定時間過期 
  8.                     .expireAfterAccess(600, TimeUnit.SECONDS) 
  9.                     // 初始的緩存空間大小 
  10.                     .initialCapacity(100) 
  11.                     // 緩存的最大條數(shù) 
  12.                     .maximumSize(500)); 
  13.             return cacheManager; 
  14.         } 

接下來就是代碼中如何來使用這個緩存了。

  1. @Override 
  2. @CachePut(value = "user"key = "#userDTO.id"
  3. public UserDTO save(UserDTO userDTO) { 
  4.     userRepository.save(userDTO); 
  5.     return userDTO; 
  6.  
  7. @Override 
  8. @CacheEvict(value = "user"key = "#id")//2 
  9. public void remove(Long id) { 
  10.     logger.info("刪除了id、key為" + id + "的數(shù)據(jù)緩存"); 
  11.  
  12. @Override 
  13. @Cacheable(value = "user",key = "#id"
  14. public UserDTO getUserById(Long id) { 
  15.     return userRepository.findOne(id); 

上述代碼中我們可以看到有幾個注解@CachePut、@CacheEvict、@Cacheable我們只需要在方法上標(biāo)上這幾個注解,我們就能夠使用緩存了,我們分別來介紹下這幾個注解。

@Cacheable

@Cacheable它是既可以標(biāo)注在類上也可以標(biāo)注在方法上,當(dāng)它標(biāo)記在類上的時候它表述這個類上面的所有方法都會支持緩存,同樣的 當(dāng)它作用在法上面時候它表示這個方法是支持緩存的。比如上面我們代碼中的getUserById這個方法第一次緩存里面沒有數(shù)據(jù),我們會去查詢DB,但是第二次來查詢的時候就不會走DB查詢了,而是直接從緩存里面拿到結(jié)果就返回了。

value 屬性

  • @Cacheable的value屬性是必須指定的,其表示當(dāng)前方法的返回值是會被緩存在哪個Cache上的,對應(yīng)Cache的名稱。

key

  • @Cacheable的key 有兩種方式一種是我們自己顯示的去指定我們的key,還有一種默認(rèn)的生成策略,默認(rèn)的生成策略是SimpleKeyGenerator這個類,這個生成key的方式也比較簡單我們可以看下它的源碼:
  1. public static Object generateKey(Object... params) { 
  2.         // 如果方法沒有參數(shù) key就是一個 new SimpleKey() 
  3.   if (params.length == 0) { 
  4.    return SimpleKey.EMPTY; 
  5.   } 
  6.   // 如果方法只有一個參數(shù) key就是當(dāng)前參數(shù) 
  7.   if (params.length == 1) { 
  8.    Object param = params[0]; 
  9.    if (param != null && !param.getClass().isArray()) { 
  10.     return param; 
  11.    } 
  12.   } 
  13.   // 如果key是多個參數(shù),key就是new SimpleKey ,不過這個SimpleKey對象的hashCode 和Equals方法是根據(jù)方法傳入的參數(shù)重寫的。 
  14.   return new SimpleKey(params); 
  15.  } 

上述代碼還是非常好理解的分為三種情況:

  • 方法沒有參數(shù),那就new使用一個全局空的SimpleKey對象來作為key。
  • 方法就一個參數(shù),就使用當(dāng)前參數(shù)來作為key
  • 方法參數(shù)大于1個,就new一個SimpleKey對象來作為key,new 這個SimpleKey的時候用傳入的參數(shù)重寫了SimpleKey的hashCode和equals方法, 至于為啥需要重寫的原因話,就跟Map用自定義對象來作為key的時候必須要重寫hashCode和equals方法原理是一樣的,因為caffein也是借助了ConcurrentHashMap來實現(xiàn),

小結(jié)

上述代碼我們可以發(fā)現(xiàn)默認(rèn)生成key只跟我們傳入的參數(shù)有關(guān)系,如果我們有一個類里面如果存在多個沒有參數(shù)的方法,然后我們使用了默認(rèn)的緩存生成策略的話,就會造成緩存丟失?;蛘呔彺嫦嗷ジ采w,或者還有可能會發(fā)生ClassCastException 因為都是使用同一個key。比如下面這代碼就會發(fā)生異常(ClassCastException)。

  1. @Cacheable(value = "user"
  2.   public UserDTO getUser() { 
  3.       UserDTO userDTO = new UserDTO(); 
  4.       userDTO.setUserName("Java金融"); 
  5.       return userDTO; 
  6.   } 
  7.   @Cacheable(value = "user"
  8.   public UserDTO2 getUser1() { 
  9.       UserDTO2 userDTO2 = new UserDTO2(); 
  10.       userDTO2.setUserName2("javajr.cn"); 
  11.       return userDTO2; 
  12.   } 

所以一般不怎么推薦使用默認(rèn)的緩存生成key的策略。如果非要用的話我們最好自己重寫一下,帶上方法名字等。類似于如下代碼:

  1. @Component 
  2. public class MyKeyGenerator extends SimpleKeyGenerator { 
  3.  
  4.     @Override 
  5.     public Object generate(Object target, Method method, Object... params) { 
  6.         Object generate = super.generate(target, method, params); 
  7.         String format = MessageFormat.format("{0}{1}{2}", method.toGenericString(), generate); 
  8.         return format; 
  9.     } 

自定義key

我們可以通過Spring的EL表達(dá)式來指定我們的key。這里的EL表達(dá)式可以使用方法參數(shù)及它們對應(yīng)的屬性。使用方法參數(shù)時我們可以直接使用“#參數(shù)名”或者“#p參數(shù)index”這也是我們比較推薦的做法:

  1. @Cacheable(value="user"key="#id"
  2.  public UserDTO getUserById(Long id) { 
  3.      UserDTO userDTO = new UserDTO(); 
  4.      userDTO.setUserName("java金融"); 
  5.      return userDTO; 
  6.  } 
  7.  @Cacheable(value="user"key="#p0"
  8.  public UserDTO getUserById1(Long id) { 
  9.      return null
  10.  } 
  11.  @Cacheable(value="user"key="#userDTO.id"
  12.  public UserDTO getUserById2(UserDTO userDTO) { 
  13.      return null
  14.  } 
  15.  @Cacheable(value="user"key="#p0.id"
  16.  public UserDTO getUserById3(UserDTO userDTO) { 
  17.      return null
  18.  } 

@CachePut

@CachePut指定的屬性是和@Cacheable一樣的,但是它們兩個是有區(qū)別的,@CachePut標(biāo)注的方法不會先去查詢緩存是否有值,而是每次都會先去執(zhí)行該方法,然后把結(jié)果返回,并且結(jié)果也會緩存起來。

為什么是這樣的一個流程我們可以去看看它的源碼關(guān)鍵代碼就是這一行,

  1. Cache.ValueWrapper cacheHit = findCachedItem(contexts.get(CacheableOperation.class)); 

當(dāng)我們使用方法上有@Cacheable注解的時候再contexts里面會把CacheableOperation加入進(jìn)去,只有contexts.get(CacheableOperation.class)取到的內(nèi)容不為空的話,才會去從緩存里面取內(nèi)容,否則的話cacheHit會直接返回null。至于contexts什么時候加入CacheableOperation的話我們看下SpringCacheAnnotationParser#parseCacheAnnotations這個方法就會明白的。具體的源碼就不展示了,感興趣的可以自己去翻。

@CacheEvict

把緩存中數(shù)據(jù)刪除,用法跟前面兩個注解差不多有value和key屬性,需要注意一點的是它多了一個屬性beforeInvocation

  • beforeInvocation 這個屬性需要注意下它的默認(rèn)值是false,false代表的意思是再執(zhí)調(diào)用方法之前不刪除緩存,只有方法執(zhí)行成功之后才會去刪除緩存。設(shè)置為true的話調(diào)用方法之前會去刪除一下緩存,方法執(zhí)行成功之后還會去調(diào)用刪除緩存這樣就是雙刪了。如果方法執(zhí)行異常的話就不會去刪除緩存。
  • allEntrie 是否清空所有緩存內(nèi)容,默認(rèn)值為 false,如果指定為 true,則方法調(diào)用后將立即清空所有緩存

@Caching

這是一個組合注解集成了上面三個注解,有三個屬性:cacheable、put和evict,分別用于來指定@Cacheable、@CachePut和@CacheEvict。

小結(jié)

第二種方式是侵入式的,它的實現(xiàn)原理也比較簡單就是通過切面的方法攔截器來實現(xiàn),攔截所有的方法,它的核心代碼如下:看起來就跟我們的業(yè)務(wù)代碼差不了多少,感興趣的也可以去瞅一瞅。

  1. if (contexts.isSynchronized()) { 
  2.    CacheOperationContext context = contexts.get(CacheableOperation.class).iterator().next(); 
  3.    if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) { 
  4.     Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT); 
  5.     Cache cache = context.getCaches().iterator().next(); 
  6.     try { 
  7.      return wrapCacheValue(method, cache.get(key, () -> unwrapReturnValue(invokeOperation(invoker)))); 
  8.     } 
  9.     catch (Cache.ValueRetrievalException ex) { 
  10.      // The invoker wraps any Throwable in a ThrowableWrapper instance so we 
  11.      // can just make sure that one bubbles up the stack. 
  12.      throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause(); 
  13.     } 
  14.    } 
  15.    else { 
  16.     // No caching required, only call the underlying method 
  17.     return invokeOperation(invoker); 
  18.    } 
  19.   } 
  20.  
  21.  
  22.   // Process any early evictions 
  23.   // beforeInvocation 屬性是否為true,如果是true就刪除緩存 
  24.   processCacheEvicts(contexts.get(CacheEvictOperation.class), true
  25.     CacheOperationExpressionEvaluator.NO_RESULT); 
  26.  
  27.   // Check if we have a cached item matching the conditions 
  28.   Cache.ValueWrapper cacheHit = findCachedItem(contexts.get(CacheableOperation.class)); 
  29.  
  30.   // Collect puts from any @Cacheable miss, if no cached item is found 
  31.   List<CachePutRequest> cachePutRequests = new LinkedList<>(); 
  32.   if (cacheHit == null) { 
  33.    collectPutRequests(contexts.get(CacheableOperation.class), 
  34.      CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests); 
  35.   } 
  36.  
  37.   Object cacheValue; 
  38.   Object returnValue; 
  39.  
  40.   if (cacheHit != null && !hasCachePut(contexts)) { 
  41.    // If there are no put requests, just use the cache hit 
  42.    cacheValue = cacheHit.get(); 
  43.    returnValue = wrapCacheValue(method, cacheValue); 
  44.   } 
  45.   else { 
  46.    // Invoke the method if we don't have a cache hit 
  47.    returnValue = invokeOperation(invoker); 
  48.    cacheValue = unwrapReturnValue(returnValue); 
  49.   } 
  50.  
  51.   // Collect any explicit @CachePuts 
  52.   collectPutRequests(contexts.get(CachePutOperation.class), cacheValue, cachePutRequests); 
  53.  
  54.   // Process any collected put requests, either from @CachePut or a @Cacheable miss 
  55.   for (CachePutRequest cachePutRequest : cachePutRequests) { 
  56.    cachePutRequest.apply(cacheValue); 
  57.   } 
  58.  
  59.   // Process any late evictions 
  60.   processCacheEvicts(contexts.get(CacheEvictOperation.class), false, cacheValue); 
  61.  
  62.   return returnValue; 
  63.  } 

結(jié)束

由于自己才疏學(xué)淺,難免會有紕漏,假如你發(fā)現(xiàn)了錯誤的地方,還望留言給我指出來,我會對其加以修正。

感謝您的閱讀,十分歡迎并感謝您的關(guān)注。 

站在巨人的肩膀上摘蘋果: https://www.cnblogs.com/fashflying/p/6908028.html#!comments

責(zé)任編輯:武曉燕 來源: java金融
相關(guān)推薦

2024-12-03 14:38:07

CaffeineRedis二級緩存

2021-07-11 18:06:18

緩存過期淘汰

2024-10-28 07:15:00

SpringBoot緩存預(yù)熱數(shù)據(jù)加載

2024-12-18 17:20:07

緩存預(yù)熱緩存系統(tǒng)Spring

2024-12-06 10:02:46

2024-07-25 14:04:16

2025-03-26 03:25:00

SpringGuavaCaffeine

2022-03-15 08:22:31

Ehcachespring緩存

2022-03-31 13:58:37

分布式SpringRedis

2025-03-20 10:50:08

RedisCaffeine緩存監(jiān)控

2024-01-19 14:03:59

Redis緩存系統(tǒng)Spring

2012-02-08 11:01:53

HibernateJava

2022-03-18 13:59:46

緩存RedisCaffeine

2023-05-05 18:38:33

多級緩存Caffeine開發(fā)

2025-03-12 08:42:28

2011-06-01 09:03:12

Android 緩存

2024-01-03 21:50:32

緩存機制請求

2025-04-23 09:31:30

2018-09-12 19:46:53

數(shù)據(jù)庫MySQLRedis

2020-01-10 15:42:13

SpringBootRedis數(shù)據(jù)庫
點贊
收藏

51CTO技術(shù)棧公眾號