Spring 低版本基于GuavaCacheManager的本地内存

缓存在很多场景下都是相当有用的。例如,计算或检索一个值的代价很高,并且对同样的输入需要不止一次获取
值的时候,就应当考虑使用缓存。


Guava Cache 与 ConcurrentMap 很相似,但也不完全一样。最基本的区别是 ConcurrentMap 会一直保存所
有添加的元素,直到显式地移除。相对地,Guava Cache 为了限制内存占用,通常都设定为自动回收元素。在
某些场景下,尽管 LoadingCache 不回收元素,它也是很有用的,因为它会自动加载缓存。

通常来说,Guava Cache 适用于:
• 你愿意消耗一些内存空间来提升速度。
• 你预料到某些键会被查询一次以上。
• 缓存中存放的数据总量不会超出内存容量。(Guava Cache 是单个应用运行时的本地缓存。它不把数据存
放到文件或外部服务器。如果这不符合你的需求,请尝试 Memcached 这类工具)
如果你的场景符合上述的每一条,Guava Cache 就适合你。
如同范例代码展示的一样,Cache 实例通过 CacheBuilder 生成器模式获取,但是自定义你的缓存才是最有趣的
部分。


注:如果你不需要 Cache 中的特性,使用 ConcurrentHashMap 有更好的内存效率——但 Cache 的大多数特
性都很难基于旧有的 ConcurrentMap 复制,甚至根本不可能做到。

基于spring的GuavaCacheManager 配置

pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>

spring支持的本地内存

配置GuavaCacheManager

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;

/**
 * @author Created by niugang on 2019/4/11/10:44
 */
@Configuration
@EnableCaching(proxyTargetClass = true)
public class CustomGuavaCacheConfig {
    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterWrite(3600, TimeUnit.SECONDS).maximumSize(1000));
        return cacheManager;
    }

}

测试

缓存menu分页信息

移除menu所有缓存

                                                                        微信公众号

                                               

                                                                             JAVA程序猿成长之路

                          分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。 

原文地址:https://www.cnblogs.com/niugang0920/p/12186434.html