Caffeine usage

Caffeine is a rewritable version of Java8 using Guava buffer, 2.0 will be substituted in the Guava Spring Boot. If Caffeine occurs, CaffeineCacheManager will be automatically configured. Use spring.cache.cache-names attribute cache can be created at startup, and can be customized (in order) by the following configuration:

  • spring.cache.caffeine.spec: the definition of special cache
  • com.github.benmanes.caffeine.cache.CaffeineSpec: bean定义
  • com.github.benmanes.caffeine.cache.Caffeine: bean定义

For example, the following configuration creates a cache foo and bar, the maximum number of 500, survival time of 10 minutes:

spring.cache.cache-names=foo,bar
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

In addition, if the definition of com.github.benmanes.caffeine.cache.CacheLoader, it will be automatically linked to CaffeineCacheManager. Since the association will be CacheLoader all caches managed by the cache manager, it must be defined as CacheLoader <Object, Object>, automatic configuration ignores all generic types.

1. dependence introduction

  <properties>
    <caffeine.cache.version>2.7.0</caffeine.cache.version>
  </properties>

  <dependencies>
    <!-- Spring boot Cache-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!--for caffeine cache-->
    <dependency>
      <groupId>com.github.ben-manes.caffeine</groupId>
      <artifactId>caffeine</artifactId>
      <version>${caffeine.cache.version}</version>
    </dependency>
   </dependencies>

2.configuration

 1 @EnableCaching
 2 @Configuration
 3 public class CaffeineCacheConfig {
 4     public static final Integer CAFFEINE_MAXSIZE = PropertyUtil.getInt("caffeine.maxsize", "10000");
 5     public static final Integer CAFFEINE_EXPIRE_TIME = PropertyUtil.getInt("caffeine.expire.time", "3");
 6 
 7     /**
 8      * 创建基于Caffeine的Cache Manager
 9      * @return
10      */
11     @Bean("caffeineCacheManager")
12     public CacheManager CaffeineCacheManager() {
13         CaffeineCacheManager cacheManager = new CaffeineCacheManager();
14 
15         cacheManager.setCaffeine(Caffeine.newBuilder().recordStats()
16                         .expireAfterWrite(CAFFEINE_EXPIRE_TIME, TimeUnit.SECONDS)
17                         .maximumSize(CAFFEINE_MAXSIZE));
18 
19         return cacheManager;
20     }
21 
22 }

Use @EnableCaching annotation let Spring Boot open support for caching

Caffeine configuration instructions:

  • initialCapacity = [integer]: the initial buffer space
  • maximumSize = [long]: The maximum number of cache
  • maximumWeight = [long]: maximum weight cache weight
  • expireAfterAccess = [duration]: after the last write access after a fixed time has expired or
  • expireAfterWrite = [duration]: elapsed after writing the last fixed time expired
  • refreshAfterWrite = [duration]: After creating the cache or the most recent update the cache after a fixed time interval, refresh the cache
  • weakKeys: Open a weak reference key
  • weakValues: Open a weak reference value of
  • softValues: Open the value of the soft references
  • recordStats: the development of statistical functions

note:

  • When expireAfterWrite and expireAfterAccess colleagues present to expireAfterWrite prevail.
  • maximumSize and can not be used simultaneously maximumWeight
  • weakValues ​​and can not be used simultaneously softValues

3.service

 1 @Service("caffeineCacheService")
 2 public class CaffeineCacheServiceImpl {
 3     @Autowired
 4     CacheManager caffeineCacheManager;
 5 
 6     private final static String DEFAULT_CACHE = "default";
 7 
 8     public <T> T getValue(Object key) {
 9         if(key == null) return null;
10 
11         Cache cache = caffeineCacheManager.getCache(DEFAULT_CACHE);
12         if(cache != null) {
13             Cache.ValueWrapper wrapper = cache.get(key);
14             if (wrapper != null)
15                 return (T) wrapper.get();
16         }
17 
18         return null;
19     }
20 
21     public <T> T getValue(String cacheName, Object key) {
22         if(cacheName == null || key == null) return null;
23 
24         Cache cache = caffeineCacheManager.getCache(cacheName);
25         if(cache != null) {
26             Cache.ValueWrapper wrapper = cache.get(key);
27             if (wrapper != null)
28                 return (T) wrapper.get();
29         }
30 
31         return null;
32     }
33 
34     public void putValue(Object key, Object value) {
35         if(key == null || value == null) return;
36 
37         Cache cache = caffeineCacheManager.getCache(DEFAULT_CACHE);
38         if(cache != null) {
39             cache.put(key, value);
40         }
41     }
42 
43     public void putValue(String cacheName, Object key, Object value) {
44         if(cacheName == null || key == null || value == null) return;
45 
46         Cache cache = caffeineCacheManager.getCache(cacheName);
47         if(cache != null) {
48             cache.put(key, value);
49         }
50     }
51 }

Which get (key) just returned ValueWrapper, need to get the specific value method. I looked caffeineCacheManager.getCache method, and normally can not find the cache when creates a new cache and put the map back in cachemap, but it looked a source method marked @Nullable, to rigorous codes, select the judgment null .

4. Examples

 1     private static Integer uuid = 0;
 2     @Cacheable(value = DEFAULT_CACHE, key = "#pin")
 3     public Integer getUUid(String pin) {
 4         /*
 5         if(getValue(pin) != null) {
 6             return getValue(pin);
 7         }*/
 8 
 9         return uuid++;
10     }

 

Attached: spring cache related notes introduce @ Cacheable, @ CachePut, @ CacheEvict

@Cacheable
@Cacheable is used to declare the method is cacheable. The result is stored into cache for subsequent use without performing the actual process parameters during the same call. Values directly from the cache. The simplest format of the need for cache name.
E.g:

1 @Cacheable("books")
2 public Book findBook(ISBN isbn) {...}

In the above code fragment, findBook cache method named books like association. Each time the method is called, it checks whether the request has been executed in the cache, in order to avoid repeated. Although in most cases, only one cache is declared, annotation allows you to specify more than one name in order to use multiple caches. In this case, prior to performing the method, the method performed before each cache checks, as long as there is a cache hit, i.e., returns the associated value directly from the cache.
Even if not actually perform caching method, all other cache does not contain this value will also be updated.
E.g:

1 @Cacheable({"books", "isbns"})
2 public Book findBook(ISBN isbn) {...}

Default key generation:
The default key is generated according to the following rules:
- If there is no argument, 0 is used as a key
- if only one parameter, the parameter used as the key
- and if a plurality of parameters, all parameters hashCode containing as the key

Custom key generation:
when the plurality of parameters when the target method, the parameters are not suitable for caching some logic
, such as:

1 @Cacheable("books")
2 public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

Which checkWarehouse, includeUsed not suitable as a cache key. In view of this situation, Cacheable allow key attribute specifies the key generation, and Support SpringEL expressions. (Recommended method)
Look at some examples:

 1 @Cacheable(cacheNames="books", key="#isbn")
 2 public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
 3 
 4 @Cacheable(cacheNames="books", key="#isbn.rawNumber")
 5 public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
 6 
 7 @Cacheable(cacheNames="books", key="T(someType).hash(#isbn)")
 8 public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
 9 
10 @Cacheable(cacheNames="books", key="#map['bookid'].toString()")
11 public Book findBook(Map<String, Object> map)

Cache synchronization sync:
in a multithreaded environment, some operations may use the same argument synchronous calls. By default, the cache does not lock any resources that may result in multiple computing, and in violation of the purpose of the cache. For these particular cases, the underlying attribute may indicate that the sync lock the cache, so that only one thread can enter the calculation, while other threads are blocked until the update returns the result to the buffer.
example:

1 @Cacheable(cacheNames="foos", sync="true")
2 public Foo executeExpensiveOperation(String id) {...}

Property condition:
Sometimes, a method has been cached may not be suitable (for example: It may depend on the given parameters). Property condition support this feature to specify boolean value can be evaluated by SpEL expression, it is true only cache (evaluated before the method execution).
example:

1 @Cacheable(cacheNames="book", condition="#name.length < 32")
2 public Book findBook(String name)

In addition, unless there is a property that can be used is to decide whether to add to the cache. The difference is that with the condition, unless the expression is evaluated after the method call. If it returns false, only into the cache (with the condition opposite). Example #result refers Return value:

1 @Cacheable(cacheNames="book", condition="#name.length < 32", unless="#result.name.length > 5"")
2 public Book findBook(String name)


@CachePut
If the cache needs to be updated, and does not interfere with the method of execution, you can use annotations @CachePut. Methods @CachePut marked not to check in before the results was performed before the existence of the cache, but each time the implementation of the method, and the results stored in the form of key-value pairs specified cache.

1 @CachePut(cacheNames="book", key="#isbn")
2 public Book updateBook(ISBN isbn, BookDescriptor descriptor)

Note: You should avoid @CachePut and @Cacheable used simultaneously.

@CacheEvict
the Spring Cache will not only support data cache, the cache also supports data deletion. This procedure is often used to remove outdated or unused data from the cache.
@CacheEvict asked to specify one or more buffers, so that all affected. In addition, it also provides an extra parameter allEntries. It indicates whether all the elements need to clear the cache. The default is false, meaning not needed. When you specify allEntries is true, Spring Cache ignores the specified key. Sometimes we need to look at Cache to clear all of the elements.

1 @CacheEvict(cacheNames="books", allEntries=true)
2 public void loadBooks(InputStream batch)

Clear operation default after successful execution of the corresponding method is triggered, it will not trigger the clearing operation that is because if a method throws an exception and failed to return. Use beforeInvocation to change the trigger cleanup time, when we specify the property value is true, Spring will clear the specified elements in the cache before calling the method.

1 @CacheEvict(cacheNames="books", beforeInvocation=true)
2 public void loadBooks(InputStream batch)

@CacheConfig
Sometimes there may be a plurality of class cache operation, the cache operations which may be repeated. This time can be used @CacheConfig

1 @CacheConfig("books")
2 public class BookRepositoryImpl implements BookRepository {
3 
4 @Cacheable
5 public Book findBook(ISBN isbn) {...}
6 }

@CacheConfig is a class-level annotations, allowing the name of the shared cache, KeyGenerator, CacheManager and CacheResolver.
This operation will be overwritten.

Open the cache comment
java class configuration:

1 @Configuration
2 @EnableCaching
3 public class AppConfig {
4 }

XML configuration:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

<cache:annotation-driven />

</beans>

 

Guess you like

Origin www.cnblogs.com/fnlingnzb-learner/p/11025565.html