🐧GuavaCache简单使用

一、概述

GuavaCache是什么?

Guava Cache是Google开发的一个功能强大的内存缓存库,它提供了灵活、高效和易用的缓存功能,用于提升应用程序的性能和响应速度。Guava Cache实现了LRU(Least Recently Used,最近最久未使用)算法,根据缓存项的访问频率和时间来自动管理缓存。

以下是Guava Cache的一些主要特点和功能:

  1. 简单易用:Guava Cache提供了简洁清晰的API,使得创建和管理缓存变得非常方便。
  2. 缓存加载:Guava Cache支持自动加载缓存项,当缓存中不存在某个键的值时,可以通过自定义的加载方法来自动获取并存储值。
  3. 缓存过期:可以设置缓存项的过期时间,当缓存项超过指定的时间未被访问时,会自动从缓存中移除。
  4. 缓存刷新:可以设置缓存项的刷新时间,当缓存项超过指定的时间时,下一次访问该缓存项时会自动刷新。
  5. 缓存回收:Guava Cache提供了不同的回收策略,如基于大小、基于权重或手动移除,以控制缓存项的数量和占用的内存。
  6. 缓存统计:Guava Cache可以统计缓存的命中率、加载数量等信息,通过这些统计信息可以监控和优化缓存性能。
  7. 弱引用和软引用:可以选择是否使用弱引用或软引用来存储缓存的键或值,以防止内存溢出。
  8. 并发安全:Guava Cache在并发访问时是线程安全的,可以在多线程环境下安全地使用。

总之,Guava Cache是一个强大而灵活的缓存库,提供了多种配置选项和功能,可用于提升应用程序的性能和效率,特别是对于需要缓存数据的场景非常有用。

GuavaCache优势和劣势

Guava缓存(Guava Cache)具有以下优势和劣势:

优势:

  1. 简单易用:Guava缓存提供了简单易用的API,使得缓存的创建和管理变得非常方便。
  2. 高性能:Guava缓存实现了LRU(Least Recently Used)缓存策略,支持高性能的内存缓存,可以提供快速的访问速度。
  3. 内存控制:Guava缓存提供了多种控制缓存大小和清理策略的方式,可以根据实际需求进行灵活配置,避免过多占用内存。
  4. 强大的功能:Guava缓存支持缓存项的过期、刷新、加载等功能,可以应对各种不同的缓存需求。
  5. 统计功能:Guava缓存可以统计缓存的使用情况,例如命中率、加载数量等,便于性能监控和优化。

劣势:

  1. 单进程限制:Guava缓存仅适用于单进程应用程序,不能进行分布式缓存。
  2. 不支持持久化:Guava缓存不支持将缓存数据持久化到磁盘或其他介质,只能在内存中缓存数据。
  3. 缓存不一致:在多线程环境中,当缓存过期或失效时,可能会出现多个线程同时加载数据的情况,可能导致缓存不一致的问题。

需要根据具体的需求和场景来评估Guava缓存的优势和劣势,并选择合适的缓存解决方案。

二、SpringBoot下如何使用

这里就只贴出关于Guava缓存的设置,Springboot基本配置这里就不写了;

实现的功能是:随便输入字符,将字符作为key,当前时间作为value进行存储;

1、引入依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

2、缓存配置类

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * 缓存配置类
 * @author zhixi
 */
@Configuration
public class CacheConfig {
    
    @Bean
    public Cache<String, String> myCache() {
        return CacheBuilder.newBuilder()
                // 设置缓存的过期时间为1小时
                .expireAfterWrite(1, TimeUnit.HOURS)
                // 设置缓存的最大容量
                .maximumSize(100)
                .build();
    }
}

3、处理缓存的值  

import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class CacheService {

    private final Cache<String, String> cache;
    
    @Autowired
    public CacheService(Cache<String, String> cache) {
        this.cache = cache;
    }
    
    public String getValueFromCache(String key) {
        // 从缓存中获取值
        String value = cache.getIfPresent(key);
        if (value == null) {
            // 如果缓存中没有对应的值,则从其他途径获取值,并放入缓存中
            value = getValueFromOtherSource(key);
            cache.put(key, value);
        }
        return value;
    }
    
    private String getValueFromOtherSource(String key) {
        // TODO:从其他途径获取值的逻辑
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}

4、Controller

import com.zhixi.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangzhixi
 * @version 1.0
 * @description
 * @date 2023-06-25 11:44
 */
@RequestMapping("/my")
@RestController
public class MyController {
    @Autowired
    private CacheService cacheService;

    @GetMapping("/test/{key}")
    public String test(@PathVariable String key) {
        return cacheService.getValueFromCache(key);
    }
}

5、测试:自行验证

http://localhost:8080/my/test/1

http://localhost:8080/my/test/2

posted @ 2023-06-25 12:34  Java小白的搬砖路  阅读(229)  评论(0编辑  收藏  举报