Guava入门~Guava caches

本文介绍了Guava的Cache接口及LoadingCache的使用,包括put、get、getIfPresent、invalidate等方法,展示了如何加载和刷新缓存,并通过示例测试了缓存加载只调用一次及过期后重新加载的行为。
摘要由CSDN通过智能技术生成

Cache 接口

put(key,value):往缓存中添加值;

V value = cache.get(key, Callable<? Extends V> value):从缓存中获取值;

// 等价
value = cache.get(key);
if(value == null){
	value = someService.retrieveValue();
	cache.put(key,value);
}

如果不想执行异步任务,可以使用Callables

Callable<String> value = Callables.returning("Foo");

cache.get(key,Callables.returning(someService.retrieveValue());

getIfPresent(key):如果存在返回value,否则null;

丢弃缓存

invalidate(key)

invalidateAll()

invalidateAll(Iterable<?> keys)

LoadingCache

Book book = loadingCache.get(id);

Loading values

ImmutableMap<key,value> map = cache.getAll(Iterable<? Extends key>);

Refreshing values in the cache

refresh(key);

示例

package bbejeck.guava.chapter6.cache;

import bbejeck.guava.common.model.TradeAccount;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;

/**
 * User: Bill Bejeck
 * Date: 7/22/13
 * Time: 10:53 PM
 */
public class LoadingCacheTest {
    private CacheLoader<String, TradeAccount> cacheLoader = mock(CacheLoader.class);

    @Test
    public void testCacheLoaderOnlyCalledOnce() throws Exception {
        TradeAccount expectedTradeAccount = new TradeAccount.Builder().balance(250000.12).build();
        when(cacheLoader.load("223")).thenReturn(expectedTradeAccount);
        LoadingCache<String, TradeAccount> tradeAccountCache = CacheBuilder.newBuilder()
                .maximumSize(5000L)
                .build(cacheLoader);

        TradeAccount tradeAccount = tradeAccountCache.get("223");
        assertThat(tradeAccount, is(expectedTradeAccount));

        for (int i = 0; i < 10; i++) {
            TradeAccount tradeAccount1 = tradeAccountCache.get("223");
            assertThat(tradeAccount1, is(expectedTradeAccount));
        }
        verify(cacheLoader, times(1)).load("223");
    }

    @Test
    public void testCacheLoaderCalledInitiallyAndAfterExpiration() throws Exception {
        TradeAccount expectedTradeAccount = new TradeAccount.Builder().balance(250000.12).build();
        when(cacheLoader.load("223")).thenReturn(expectedTradeAccount);
        LoadingCache<String, TradeAccount> tradeAccountCache = CacheBuilder.newBuilder()
                .maximumSize(5000L)
                .expireAfterAccess(500l, TimeUnit.MILLISECONDS)
                .build(cacheLoader);

        TradeAccount tradeAccount = tradeAccountCache.get("223");
        assertThat(tradeAccount, is(expectedTradeAccount));

        Thread.sleep(1000);

        TradeAccount tradeAccount1 = tradeAccountCache.get("223");
        assertThat(tradeAccount1, is(expectedTradeAccount));
        verify(cacheLoader, times(2)).load("223");
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值