Spring boot local cache (guava and caffeine)

1. Scene description

Because the project needs to use local caching, specifically why not redis, etc., do not discuss, record the process, hoping to help needy friends.

2. Solutions

2.1 Use guava as a local cache

The initial idea is to use guava, because there is guava's denpency in the project itself.

2.1.1 pom file

Three dependencies are required, as follows:

  <!--Software Lao Wang 1-->
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
  <!--Software Lao Wang 2-->
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.18.RELEASE</version>
  </dependency>
   <!--Software Lao Wang 3-->
   <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>24.0-jre</version>
     </dependency>

2.1.2 java class

(1)GuavaCacheManager

Create new bean s, return and configure guava's Guava Cache Manager.

import com.google.common.cache.CacheBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;
/**
* 
* @auther: Software old king
*/
@Configuration
@EnableCaching
public class GuavaCacheConfig {

    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(
                CacheBuilder.newBuilder().
                        expireAfterWrite(6, TimeUnit.HOURS).
                        maximumSize(1000)); //Software Lao Wang, 6 hours expired, maximum 1000
        return cacheManager;
    }
}

(2) spring annotation tags use caching

/**
* 
* @auther: Software old king
*/
  @Cacheable(value = "ruanjianlaowang")
    public VO<UserParm> getUserInfo(String token) {
        VO<UserParm> vo = userauthClient.verifyToken(token);
        return vo;
    }

guava local cache completion.

2.2 Local Caching Scheme Provided by Spring Framework

Abstract classes have been provided in spring. By default, we only need to configure loading jar package and configure type. But since spring 5, we have removed guava and replaced it with caffeine. Spring has tested it. As a local cache, caffeine is much higher than guava. We have also changed to caffeine as a local cache.

springboot and guava, caffeine and other local caches, spring boot 1 when there is guava, spring boot 2 on the guava cache interface removed, so the previous guava local caches need to define Configuration, in this case, only in the configuration file to define the type will be automatically injected.

2.3 caffeine local cache

2.3.1 pom file
        <!--Software old king-->
       <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.0</version>
        </dependency>
2.3.2 Profile
spring:
   cache:
      type: caffeine
      cache-names: bc.gateway.ut
      caffeine:
#        spec: maximumSize=5000,expireAfterWrite=20s
         spec: maximumSize=5000,expireAfterAccess=3600s

Specific parameter meanings:

/**
*@ Auher: Lao Wang of Software
*/
Initial capacity = [integer]: initial cache size
 Maximum Size = [long]: Maximum number of caches
 Maximum Weight = [long]: Maximum weight of cache
 expireAfterAccess=[duration]: expires after a fixed time after the last write or access
 expireAfterWrite=[duration]: expires after a fixed time after the last write
 refreshAfterWrite=[duration]: refresh the cache at a fixed interval after creating or last updating the cache
2.3.3 How to use spring's label or not to move:
/**
* 
* @auther: Software old king
*/
  @Cacheable(value = "ruanjianlaowang")
    public VO<UserParm> getUserInfo(String token) {
        VO<UserParm> vo = userauthClient.verifyToken(token);
        return vo;
    }

2.4 Notes on spring Cache Tags

Four labels:

(1) @Cacheable, first query in the cache, if not, enter the method to execute, and return the value to the cache after execution;

(2) @CachePut, without query judgment, directly adds or updates cached content, similar to add or update;

(3) @CacheEvict, cleared directly, similar to delete.

(4) @Caching, 1,2,3 combinations

value The name of the cache, defined in the spring configuration file, must specify at least one For example: @Cacheable(value="laowang_cache1")@Cacheable(value={""laowang_cache1","laowang_cache2"}
key The cached key can be empty, if specified to be written in accordance with the SpEL expression, and if not specified, by default it is combined with all the parameters of the method. @Cacheable(value="laowang_cache1",key="#userName")
condition Cache conditions can be null, written using SpEL, returned true or false, and cached only for true @Cacheable(value="laowang_cache1", condition="#userName.length()>11")

I'm "Lao Wang of Software". If you think it's OK, you can update the information in seconds. Welcome to the discussion

Tags: Programming Spring Google Java Redis

Posted on Sat, 12 Oct 2019 00:22:20 -0700 by pfdesigns