本文整理汇总了Java中com.google.common.cache.CacheLoader类的典型用法代码示例。如果您正苦于以下问题:Java CacheLoader类的具体用法?Java CacheLoader怎么用?Java CacheLoader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CacheLoader类属于com.google.common.cache包,在下文中一共展示了CacheLoader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: AccessTokenJob
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
public AccessTokenJob() {
logger.info("init");
accessTokenCache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(90, TimeUnit.MINUTES).initialCapacity(10).maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<AppIdSecret, String>() {
@Override
public void onRemoval(RemovalNotification<AppIdSecret, String> notification) {
logger.info(notification.getKey() + " was removed, cause by " + notification.getCause());
}
}).build(new CacheLoader<AppIdSecret, String>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public String load(AppIdSecret appIdSecret) throws Exception {
Token token = CommonUtil.getAccessToken(appIdSecret.getAppId(), appIdSecret.getAppSecret());
return token.getToken();
}
});
}
示例2: createFilesCache
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
private LoadingCache<Integer, Bucket> createFilesCache(final MinebdConfig config) {
Preconditions.checkNotNull(config.parentDirs);
final Integer maxOpenFiles = config.maxOpenFiles;
Preconditions.checkNotNull(maxOpenFiles);
Preconditions.checkArgument(maxOpenFiles > 0);
return CacheBuilder.newBuilder()
.maximumSize(maxOpenFiles)
.removalListener((RemovalListener<Integer, Bucket>) notification -> {
logger.debug("no longer monitoring bucket {}", notification.getKey());
try {
notification.getValue().close();
} catch (IOException e) {
logger.warn("unable to flush and close file " + notification.getKey(), e);
}
})
.build(new CacheLoader<Integer, Bucket>() {
@Override
public Bucket load(Integer key) throws Exception {
return bucketFactory.create(key);
}
});
}
示例3: casEventRepository
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
@Bean
public CasEventRepository casEventRepository() {
final LoadingCache<String, CasEvent> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(EXPIRATION_TIME, TimeUnit.HOURS)
.build(new CacheLoader<String, CasEvent>() {
@Override
public CasEvent load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
LOGGER.debug("Created an in-memory event repository to store CAS events for [{}] hours", EXPIRATION_TIME);
return new InMemoryCasEventRepository(storage);
}
示例4: mfaTrustEngine
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
@ConditionalOnMissingBean(name = "mfaTrustEngine")
@Bean
@RefreshScope
public MultifactorAuthenticationTrustStorage mfaTrustEngine() {
final LoadingCache<String, MultifactorAuthenticationTrustRecord> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(casProperties.getAuthn().getMfa().getTrusted().getExpiration(),
casProperties.getAuthn().getMfa().getTrusted().getTimeUnit())
.build(new CacheLoader<String, MultifactorAuthenticationTrustRecord>() {
@Override
public MultifactorAuthenticationTrustRecord load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
final InMemoryMultifactorAuthenticationTrustStorage m = new InMemoryMultifactorAuthenticationTrustStorage(storage);
m.setCipherExecutor(mfaTrustCipherExecutor());
return m;
}
示例5: oneTimeTokenAuthenticatorTokenRepository
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
@ConditionalOnMissingBean(name = "oneTimeTokenAuthenticatorTokenRepository")
@Bean
public OneTimeTokenRepository oneTimeTokenAuthenticatorTokenRepository() {
final LoadingCache<String, Collection<OneTimeToken>> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(EXPIRE_TOKENS_IN_SECONDS, TimeUnit.SECONDS)
.build(new CacheLoader<String, Collection<OneTimeToken>>() {
@Override
public Collection<OneTimeToken> load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
return new CachingOneTimeTokenRepository(storage);
}
示例6: CachingReEncryptionKeyProvider
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
public CachingReEncryptionKeyProvider(AbstractReEncryptionKeyProvider prov, long keyTimeoutMillis,
long eekTimeoutMillis) {
super(prov.getConf());
this.provider = prov;
reEncryptionKeyCache =
CacheBuilder.newBuilder().expireAfterAccess(keyTimeoutMillis,
TimeUnit.MILLISECONDS)
.build(new CacheLoader<ReEncryptionKeyCacheKey, ReEncryptionKeyInstance>() {
@Override
public ReEncryptionKeyInstance load(ReEncryptionKeyCacheKey key) throws Exception {
ReEncryptionKeyInstance kv = provider.createReEncryptionKey(
key.getSrcKeyName(), key.getDstKeyName());
if (kv == null) {
throw new KeyNotFoundException();
}
return kv;
}
});
transformedEEKCache =
CacheBuilder.newBuilder().expireAfterAccess(eekTimeoutMillis,
TimeUnit.MILLISECONDS)
.build();
}
示例7: AuthorizationController
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
/**
*
*/
public AuthorizationController() {
cache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(2, TimeUnit.MINUTES).initialCapacity(10).maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<String, SNSUserInfo>() {
@Override
public void onRemoval(RemovalNotification<String, SNSUserInfo> notification) {
log.info(notification.getKey() + " was removed, cause by " + notification.getCause());
}
}).build(new CacheLoader<String, SNSUserInfo>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public SNSUserInfo load(String appIdSecret) throws Exception {
return userInfoCache.get(appIdSecret);
}
});
}
示例8: FileCache
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
public FileCache(int maxSize, int concurrencyLevel) {
cache = CacheBuilder.newBuilder()
.maximumSize(maxSize)
.concurrencyLevel(concurrencyLevel)
.build(new CacheLoader<File, byte[]>() {
@SneakyThrows
@Override
public byte[] load(File key) throws Exception {
if (!key.isFile()) throw new IllegalArgumentException(key + ": not a file");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(key);
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) != -1) baos.write(buffer, 0, read);
fis.close();
return baos.toByteArray();
}
});
}
示例9: CachedGeocoder
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
/**
* Adds a cache to the given geocoder.
* @param geocoder to decorate.
*/
public CachedGeocoder(Geocoder geocoder)
{
Objects.requireNonNull(geocoder);
decorated = geocoder;
cache = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.expireAfterAccess(10, TimeUnit.MINUTES)
.build(
new CacheLoader<String, String>()
{
@Override
public String load(String key)
{
return decorated.getBoundariesWKT(key);
}
}
);
}
示例10: getMetadata
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
@Override
public Map<String, Map<String, String>> getMetadata(File f)
{
LoadingCache<String, Map<String, String>> metadata = CacheBuilder.newBuilder().build(
CacheLoader.from(new Function<String, Map<String, String>>()
{
@Override
public Map<String, String> apply(String input)
{
return Maps.newHashMap();
}
}));
for( MetadataHandler handler : pluginTracker.getBeanList() )
{
handler.getMetadata(metadata, f);
}
return metadata.asMap();
}
示例11: getFromCache
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private <T> T getFromCache(Object key, String property, final CacheLoader<String, T> loader)
{
Cache<Object, Object> map = cache.getCache();
Object ro = map.getIfPresent(key);
if( ro == null )
{
T newObj = loadFromDb(property, loader);
synchronized( map )
{
map.put(key, newObj != null ? newObj : CACHED_NULL);
return newObj;
}
}
else
{
return ro.equals(CACHED_NULL) ? null : (T) ro;
}
}
示例12: BaseProcessingUnit
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
/**
* Creates a new processing unit.
*
* @param name name.
* @param engine the engine.
* @param inQueue input queue.
* @param outQueue output queue.
*/
public BaseProcessingUnit(String name, Engine engine, EventQueue inQueue, EventQueue outQueue) {
super(name, engine);
this.inQueue = inQueue;
this.outQueue = outQueue;
long cacheExpireTime = engine.getDefaultParameters().getProcessingUnitEventProcessorCacheExpireTime();
if (cacheExpireTime >= 0) {
// Turn on the cache.
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (cacheExpireTime > 0) {
builder.expireAfterAccess(cacheExpireTime, TimeUnit.MILLISECONDS);
}
eventNameProcessorsCache = builder.build(new CacheLoader<String, Set<AtomicReference<T>>>() {
@Override
public Set<AtomicReference<T>> load(String eventName) throws Exception {
return resolveEventProcessors(eventName);
}
});
}
}
示例13: CachedScriptClassInstancePovider
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
public CachedScriptClassInstancePovider(Engine engine, Function<String, S> createScriptFunction, String format,
BiFunction<S, Class<T>, T> createInstanceFunction) {
this.createScriptFunction = createScriptFunction;
this.format = format;
this.createInstanceFunction = createInstanceFunction;
long cacheExpireTime = engine.getDefaultParameters().getScriptClassInstancePoviderCacheExpireTime();
if (cacheExpireTime >= 0) {
// Turn on the cache.
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (cacheExpireTime > 0) {
builder.expireAfterAccess(cacheExpireTime, TimeUnit.MILLISECONDS);
}
cache = builder.build(new CacheLoader<String, S>() {
@Override
public S load(String className) throws Exception {
return createScript(className);
}
});
}
}
示例14: HunspellService
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
@Inject
public HunspellService(final Settings settings, final Environment env, final Map<String, Dictionary> knownDictionaries) throws IOException {
super(settings);
this.knownDictionaries = knownDictionaries;
this.hunspellDir = resolveHunspellDirectory(settings, env);
this.defaultIgnoreCase = settings.getAsBoolean(HUNSPELL_IGNORE_CASE, false);
dictionaries = CacheBuilder.newBuilder().build(new CacheLoader<String, Dictionary>() {
@Override
public Dictionary load(String locale) throws Exception {
Dictionary dictionary = knownDictionaries.get(locale);
if (dictionary == null) {
dictionary = loadDictionary(locale, settings, env);
}
return dictionary;
}
});
if (!settings.getAsBoolean(HUNSPELL_LAZY_LOAD, false)) {
scanAndLoadDictionaries();
}
}
示例15: clientLoader
import com.google.common.cache.CacheLoader; //导入依赖的package包/类
private CacheLoader<String, DFSClient> clientLoader() {
return new CacheLoader<String, DFSClient>() {
@Override
public DFSClient load(String userName) throws Exception {
UserGroupInformation ugi = getUserGroupInformation(
userName,
UserGroupInformation.getCurrentUser());
// Guava requires CacheLoader never returns null.
return ugi.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws IOException {
return new DFSClient(NameNode.getAddress(config), config);
}
});
}
};
}