Guava缓存的使用

记录,如下:

guava缓存于本地内存中,速度要快于redis……

maven依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>25.1-jre</version>
</dependency>

配置类:


import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.annotation.Value;
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;

/**
 * Guava配置类
 */
@Configuration
@EnableCaching
public class GuavaCacheConfig {
    /** guava的过期时间设置  */
    @Value("${guava.timer}")
    private String timer;
    /** guava的最大内存大小(对象的数量)  */
    @Value("${guava.maximumSize}")
    private String maximumSize;

    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(
                CacheBuilder.newBuilder().
                        expireAfterWrite(Integer.parseInt(timer), TimeUnit.HOURS).
                        maximumSize(Integer.parseInt(maximumSize)));
        return cacheManager;
    }
}

使用:
Cacheable:将第一次请求方法的返回值,存入缓存
CacheEvict:将缓存中key对应的缓存数据清除

/**
 *  使用实例.
 *
 * value:定义cache的名称
 * key:在value中唯一标识
 *
 */
@Cacheable(value = "cacheName", key = "'KEY_'.concat(#code)")
@CacheEvict(value = "cacheName", key = "'KEY_'.concat(#code)", condition = "#isEvict")
public String flushSomeThing(String code, boolean isEvict){……}

注意:
    1 spring的版本   

    2 一个方法m1,调用同一个类里的另一个有缓存注解的方法m2:这样是不走缓存的。
        故缓存的方法一般单独写出来一个接口类

猜你喜欢

转载自blog.csdn.net/LLLLLiSHI/article/details/88058514
今日推荐