美文网首页
google Guava Cache使用

google Guava Cache使用

作者: 一个神奇的女码农 | 来源:发表于2019-07-22 17:32 被阅读0次

前言:
项目需要缓存实时数据,需要根据时间维度去定期清理缓存中的数据,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));

相关文章

  • java之guava cache应用

    google的guava cache是一个轻量级进程内缓存框架。 如何使用guava cache a. 引入方便,...

  • google Guava Cache使用

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

  • Guava Cache本地缓存使用小结

    原创文章,转载请注明原文章地址,谢谢! Guava Cache介绍 guava cache是google guav...

  • 初探guava cache实现

    王二北原创,转载请标明出处:来自王二北 1、简单介绍guava cache guava cache是Google ...

  • 高并发系统技术梳理

    缓存 缓存使用常见问题归纳Guava Cache系列之一Guava Cache系列之二Guava Cache系列之...

  • Guava Cache用法介绍

    Guava Cache的使用场景 参考1 Guava Cache用法介绍2 分布式系统缓存系列之guava cache

  • cache

    guava cache的使用

  • 2.2GuavaCache

    Guava Cache是google提供的java API开发工具包的一块。Guava Cache是一个全内存的本...

  • 2019-03-05 cache

    如何提高缓存命中率 Google Guava Cache详解及使用场景 有关于移动边缘计算(MEC)/Cloud-...

  • google Guava Cache使用(本地缓存)

    1.在多线程并发场景中往往是离不开cache的,需要根据不同的场景来选择不同的cache, cache就是为了提升...

网友评论

      本文标题:google Guava Cache使用

      本文链接:https://www.haomeiwen.com/subject/fqawlctx.html