google Guava Cache使用


前言:
项目需要缓存实时数据,需要根据时间维度去定期清理缓存中的数据,Guava Cache 就比较适合,是一个轻量的,向本地缓存的适合存储少量数据的cache;

pom 依赖:

            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>${guava.version}</version>
            </dependency> 

构建实例:

 Cache<Integer, String> cache = CacheBuilder.newBuilder()  
        //设置cache的初始大小
        .initialCapacity(10)  
        // 缓存的最大大小 
        .maximumSize(2000)
        // 缓存的最大重量 注:此功能不能与@link maximumsize结合使用。
        .maximumWeight(2000)
        //设置并发数为5,即同一时间最多只能有5个线程往cache执行写入操作  
        .concurrencyLevel(16)  
        //设置cache中的数据在写入之后的存活时间为7天  
        .expireAfterWrite(7, TimeUnit.DAYS)  
        //设置缓存多久没阅读就自动清除
        .expireAfterAccess(1,TimeUnit.DAYS)
        //构建cache实例  
        .build();

大致选了几种常用的,可以根据自己的需要构建实例;

然后让我们看下Guava Cache提供的方法:(比较懒,源码搬运工)

public interface Cache<K, V> {

  /**
   * Returns the value associated with {@code key} in this cache, or {@code null} if there is no
   * cached value for {@code key}.
   * 
   * @since 11.0
   */
  @Nullable
  V getIfPresent(Object key);

  /**
   * Returns the value associated with {@code key} in this cache, obtaining that value from {@code
   * loader} if necessary. The method improves upon the conventional "if cached, return; otherwise
   * create, cache and return" pattern. For further improvements, use {@link LoadingCache} and its
   * {@link LoadingCache#get(Object) get(K)} method instead of this one.
   *
   * <p>Among the improvements that this method and {@code LoadingCache.get(K)} both provide are:
   *
   * <ul>
   * <li>{@linkplain LoadingCache#get(Object) awaiting the result of a pending load} rather than
   *     starting a redundant one
   * <li>eliminating the error-prone caching boilerplate
   * <li>tracking load {@linkplain #stats statistics}
   * </ul>
   *
   * <p>Among the further improvements that {@code LoadingCache} can provide but this method cannot:
   *
   * <ul>
   * <li>consolidation of the loader logic to {@linkplain CacheBuilder#build(CacheLoader) a single
   *     authoritative location}
   * <li>{@linkplain LoadingCache#refresh refreshing of entries}, including {@linkplain
   *     CacheBuilder#refreshAfterWrite automated refreshing}
   * <li>{@linkplain LoadingCache#getAll bulk loading requests}, including {@linkplain
   *     CacheLoader#loadAll bulk loading implementations}
   * </ul>
   *
   * <p><b>Warning:</b> For any given key, every {@code loader} used with it should compute the same
   * value. Otherwise, a call that passes one {@code loader} may return the result of another call
   * with a differently behaving {@code loader}. For example, a call that requests a short timeout
   * for an RPC may wait for a similar call that requests a long timeout, or a call by an
   * unprivileged user may return a resource accessible only to a privileged user making a similar
   * call. To prevent this problem, create a key object that includes all values that affect the
   * result of the query. Or use {@code LoadingCache.get(K)}, which lacks the ability to refer to
   * state other than that in the key.
   *
   * <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code loader} <b>must not</b> return
   * {@code null}; it may either return a non-null value or throw an exception.
   *
   * <p>No observable state associated with this cache is modified until loading completes.
   *
   * @throws ExecutionException if a checked exception was thrown while loading the value
   * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
   *     value
   * @throws ExecutionError if an error was thrown while loading the value
   *
   * @since 11.0
   */
  V get(K key, Callable<? extends V> loader) throws ExecutionException;

  /**
   * Returns a map of the values associated with {@code keys} in this cache. The returned map will
   * only contain entries which are already present in the cache.
   *
   * @since 11.0
   */
  ImmutableMap<K, V> getAllPresent(Iterable<?> keys);

  /**
   * Associates {@code value} with {@code key} in this cache. If the cache previously contained a
   * value associated with {@code key}, the old value is replaced by {@code value}.
   *
   * <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return;
   * otherwise create, cache and return" pattern.
   *
   * @since 11.0
   */
  void put(K key, V value);

  /**
   * Copies all of the mappings from the specified map to the cache. The effect of this call is
   * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
   * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
   * if the specified map is modified while the operation is in progress.
   *
   * @since 12.0
   */
  void putAll(Map<? extends K, ? extends V> m);

  /**
   * Discards any cached value for key {@code key}.
   */
  void invalidate(Object key);

  /**
   * Discards any cached values for keys {@code keys}.
   *
   * @since 11.0
   */
  void invalidateAll(Iterable<?> keys);

  /**
   * Discards all entries in the cache.
   */
  void invalidateAll();

  /**
   * Returns the approximate number of entries in this cache.
   */
  long size();

  /**
   * Returns a current snapshot of this cache's cumulative statistics, or a set of default values if
   * the cache is not recording statistics. All statistics begin at zero and never decrease over the
   * lifetime of the cache.
   *
   * <p><b>Warning:</b> this cache may not be recording statistical data. For example, a cache
   * created using {@link CacheBuilder} only does so if the {@link CacheBuilder#recordStats} method
   * was called. If statistics are not being recorded, a {@code CacheStats} instance with zero for
   * all values is returned.
   *
   */
  CacheStats stats();

  /**
   * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to
   * the map directly affect the cache.
   *
   * <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for
   * concurrent use, but if the cache is modified (including by eviction) after the iterator is
   * created, it is undefined which of the changes (if any) will be reflected in that iterator.
   */
  ConcurrentMap<K, V> asMap();

  /**
   * Performs any pending maintenance operations needed by the cache. Exactly which activities are
   * performed -- if any -- is implementation-dependent.
   */
  void cleanUp();

因为本项目中只用到了写入,读取两种(写入的时候若key存在,则覆盖,就没有用到删除),以下只展示put,get两种方法:

存:
cache.put(MARKET_REAL_KEY.getCacheKey(vo.getSymbol()), vo);
取:
cache.getIfPresent(MARKET_REAL_KEY.getCacheKey(symbol));
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.在多线程并发场景中往往是离不开cache的,需要根据不同的场景来选择不同的cache, cache就是为了提升...
    小丸子的程序梦阅读 10,416评论 1 2
  • 原文 使用Guava cache构建本地缓存 - sameLuo的个人空间 - OSCHINA Guava Cac...
    OoLukeoO阅读 11,633评论 0 3
  • 1、对对红 记得上高中的时候,老师让同学们从家里拿些盆栽的花到学校,用来妆点...
    燕声燕语阅读 3,047评论 0 0
  • 最远的距离莫过于我在你身边 却不知道你是谁 你猛劲地吞云吐雾 挡板却无力隔断那阵阵刺鼻 来去匆匆之时 可曾留意 明...
    凭栏望江听流水阅读 1,417评论 0 0
  • sources :Python 3 programming tutorial: While Loop_Youtube
    HuafengLu阅读 1,300评论 0 0