下面列出了怎么用com.google.common.cache.CacheLoader的API类实例代码及写法,或者点击链接到github查看源代码。
public ClassLoaderCache(final SchemaRegistryClient schemaRegistryClient) {
this.schemaRegistryClient = schemaRegistryClient;
CacheLoader<String, ClassLoader> cacheLoader = new CacheLoader<String, ClassLoader>() {
@Override
public ClassLoader load(String fileId) throws Exception {
File file = getFile(fileId);
return new URLClassLoader(new URL[]{file.toURI().toURL()});
}
};
SchemaRegistryClient.Configuration configuration = schemaRegistryClient.getConfiguration();
loadingCache = CacheBuilder.newBuilder()
.maximumSize(((Number) configuration.getValue(CACHE_SIZE_KEY)).longValue())
.expireAfterAccess(((Number) configuration.getValue(CACHE_EXPIRY_INTERVAL_KEY)).longValue(),
TimeUnit.SECONDS)
.build(cacheLoader);
localJarsDir = new File((String) this.schemaRegistryClient.getConfiguration().getValue(SchemaRegistryClient.Configuration.LOCAL_JAR_PATH.name()));
ensureLocalDirsExist();
}
public DbDicService(DicStore dicStore, String pattern) {
this.dicStore = dicStore;
this.pattern = pattern;
this.name2IdCache = CacheBuilder.newBuilder()
.maximumSize(MAX_SIZE).expireAfterAccess(1, TimeUnit.DAYS)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) {
try {
return getOrCreateId(key);
} catch (EmptyResultDataAccessException e) {
return "";
}
}
});
}
@Override
protected void doInit(Map<String, ?> config) {
schemaCache = CacheBuilder.newBuilder()
.maximumSize(getCacheMaxSize(config))
.expireAfterAccess(getCacheExpiryInSecs(config), TimeUnit.SECONDS)
.build(new CacheLoader<SchemaVersionKey, S>() {
@Override
public S load(SchemaVersionKey schemaVersionKey) {
try {
return getParsedSchema(schemaVersionKey);
} catch (SchemaNotFoundException | InvalidSchemaException e) {
throw new RegistryException(e);
}
}
});
}
public static List<PriceInfo> search(String term, int limit) {
try {
Request request = Request.Get(API_URL + "search?term=" + URLEncoder.encode(term, "UTF-8") + "&limit=" + limit);
request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
if (response != null) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
return GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE);
}
}
return new ArrayList<>();
} catch (IOException | CacheLoader.InvalidCacheLoadException e) {
e.printStackTrace();
return new ArrayList<>();
}
}
/**
* @param methodName the name of the implementation method in the extension file
* @param methodParameters a mapping of field names to values for a given rule
* @param attributes a mapping of field names to attributes for a given rule
* com.facebook.buck.core.artifact.Artifact}s
* @param context mapping of build targets to {@link ProviderInfoCollection} for rules that this
* rule
*/
private SkylarkRuleContextAttr(
String methodName,
Map<String, Object> methodParameters,
Map<String, Attribute<?>> attributes,
RuleAnalysisContext context) {
this.methodName = methodName;
this.attributes = attributes;
this.postCoercionTransformValues =
CacheBuilder.newBuilder()
.build(
new CacheLoader<String, Object>() {
@Override
public Object load(String paramName) {
Object coercedValue =
Preconditions.checkNotNull(methodParameters.get(paramName));
return Preconditions.checkNotNull(attributes.get(paramName))
.getPostCoercionTransform()
.postCoercionTransform(coercedValue, context);
}
});
}
public ApplicationIdCacheImpl(
final EntityManager managementEnityManager, ManagerCache managerCache, ApplicationIdCacheFig fig) {
this.managementEnityManager = managementEnityManager;
this.managerCache = managerCache;
appCache = CacheBuilder.newBuilder()
.maximumSize(fig.getCacheSize())
.expireAfterWrite(fig.getCacheTimeout(), TimeUnit.MILLISECONDS)
.build(new CacheLoader<String, UUID>() {
@Override
public UUID load(final String key) throws Exception {
UUID appId = fetchApplicationId(key);
if ( appId == null ) {
throw new PersistenceException("Error getting applicationId");
}
return appId;
}
});
}
private LoadingCache<Long, Page<T>> buildCache(int size) {
return CacheBuilder.newBuilder().concurrencyLevel(1).initialCapacity(size).maximumSize(size)
.removalListener(new RemovalListener<Long, Page<T>>() {
@Override
public void onRemoval(RemovalNotification<Long, Page<T>> notification) {
m_recentlyExpiredPagesCache.get().put(notification.getKey(), true);
}
}).build(new CacheLoader<Long, Page<T>>() {
@Override
public Page<T> load(Long pageNo) throws Exception {
return new Page<>(pageNo, m_pageSize, m_pageLoadIntervalMillis);
}
});
}
public ThriftHiveMetastore(MetastoreLocator metastoreLocator, HiveConfig hiveConfig, ThriftMetastoreConfig thriftConfig, HdfsEnvironment hdfsEnvironment, boolean authenticationEnabled)
{
this.hdfsContext = new HdfsContext(ConnectorIdentity.ofUser(DEFAULT_METASTORE_USER));
this.clientProvider = requireNonNull(metastoreLocator, "metastoreLocator is null");
this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
this.backoffScaleFactor = thriftConfig.getBackoffScaleFactor();
this.minBackoffDelay = thriftConfig.getMinBackoffDelay();
this.maxBackoffDelay = thriftConfig.getMaxBackoffDelay();
this.maxRetryTime = thriftConfig.getMaxRetryTime();
this.maxRetries = thriftConfig.getMaxRetries();
this.impersonationEnabled = thriftConfig.isImpersonationEnabled();
this.deleteFilesOnDrop = thriftConfig.isDeleteFilesOnDrop();
this.translateHiveViews = hiveConfig.isTranslateHiveViews();
this.maxWaitForLock = thriftConfig.getMaxWaitForTransactionLock();
this.authenticationEnabled = authenticationEnabled;
this.delegationTokenCache = CacheBuilder.newBuilder()
.expireAfterWrite(thriftConfig.getDelegationTokenCacheTtl().toMillis(), MILLISECONDS)
.maximumSize(thriftConfig.getDelegationTokenCacheMaximumSize())
.build(CacheLoader.from(this::loadDelegationToken));
}
public ChallengeCompletionLogic(uSkyBlock plugin, FileConfiguration config) {
this.plugin = plugin;
storeOnIsland = config.getString("challengeSharing", "island").equalsIgnoreCase("island");
completionCache = CacheBuilder
.from(plugin.getConfig().getString("options.advanced.completionCache", "maximumSize=200,expireAfterWrite=15m,expireAfterAccess=10m"))
.removalListener(new RemovalListener<String, Map<String, ChallengeCompletion>>() {
@Override
public void onRemoval(RemovalNotification<String, Map<String, ChallengeCompletion>> removal) {
saveToFile(removal.getKey(), removal.getValue());
}
})
.build(new CacheLoader<String, Map<String, ChallengeCompletion>>() {
@Override
public Map<String, ChallengeCompletion> load(String id) throws Exception {
return loadFromFile(id);
}
}
);
storageFolder = new File(plugin.getDataFolder(), "completion");
if (!storageFolder.exists() || !storageFolder.isDirectory()) {
storageFolder.mkdirs();
}
}
public ScmSourceProviderImpl(final Function<String, PieroneOperations> pieroneOperationsProvider) {
this.pieroneOperationsProvider = pieroneOperationsProvider;
this.cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterAccess(5, MINUTES)
.build(new CacheLoader<String, Optional<Map<String, String>>>() {
@Override
public Optional<Map<String, String>> load(@Nonnull final String source) throws Exception {
final Optional<Map<String, String>> result = scmSourceFor(source);
if (!result.isPresent()) {
log.warn("Could not find scm source '{}' in Pierone", source);
}
return result;
}
});
}
public AppleDependenciesCache(TargetGraph projectGraph) {
this.depsCache =
CacheBuilder.newBuilder()
.build(
CacheLoader.from(
node -> {
ImmutableSortedSet.Builder<TargetNode<?>> defaultDepsBuilder =
ImmutableSortedSet.naturalOrder();
ImmutableSortedSet.Builder<TargetNode<?>> exportedDepsBuilder =
ImmutableSortedSet.naturalOrder();
AppleBuildRules.addDirectAndExportedDeps(
projectGraph,
node,
defaultDepsBuilder,
exportedDepsBuilder,
Optional.empty());
return new CacheItem(defaultDepsBuilder.build(), exportedDepsBuilder.build());
}));
}
@Inject
public ZookeeperLock(ZookeeperConfiguration config) {
LOCK_NAMESPACE = config.getProperty("workflow.decider.locking.namespace", "");
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.newClient(
config.getZkConnection(),
config.getZkSessiontimeoutMs(),
config.getZkConnectiontimeoutMs(),
retryPolicy
);
client.start();
zkLocks = CacheBuilder.newBuilder()
.maximumSize(CACHE_MAXSIZE)
.expireAfterAccess(CACHE_EXPIRY_TIME, TimeUnit.MINUTES)
.build(new CacheLoader<String, InterProcessMutex>() {
@Override
public InterProcessMutex load(String key) throws Exception {
return new InterProcessMutex(client, zkPath.concat(key));
}
}
);
zkPath = StringUtils.isEmpty(LOCK_NAMESPACE)
? ("/conductor/")
: ("/conductor/" + LOCK_NAMESPACE + "/");
}
@Inject
public ArchiveManager(StorageManager storageManager, Config systemConfig)
{
this.storageManager = storageManager;
this.storageCache = CacheBuilder.newBuilder()
.maximumSize(2)
.build(
new CacheLoader<ArchiveType, Storage>()
{
public Storage load(ArchiveType type)
{
return openStorage(type);
}
});
this.systemConfig = systemConfig;
this.uploadArchiveType = systemConfig.get("archive.type", ArchiveType.class, ArchiveType.DB);
this.pathPrefix = getArchivePathPrefix(systemConfig, uploadArchiveType);
this.directDownloadEnabled = systemConfig.get("archive." + uploadArchiveType + ".direct_download", Boolean.class, false);
}
@VisibleForTesting
public AmazonS3Provider(AWSCredentialsProvider credentialsProvider, String localRegionName) {
_credentialsProvider = credentialsProvider;
_localRegionName = localRegionName;
_clientsByRegion = CacheBuilder.newBuilder()
.maximumSize(4)
.build(new CacheLoader<String, AmazonS3>() {
@Override
public AmazonS3 load(String regionName) throws Exception {
return createS3ClientForRegion(regionName);
}
});
_clientsByBucket = CacheBuilder.newBuilder()
.maximumSize(10)
.build();
}
GitLabAccess(@NotNull LocalContext local, @NotNull GitLabMappingConfig config, int projectId) {
this.environment = Collections.singletonMap("GL_REPOSITORY", String.format("project-%s", projectId));
final GitLabContext context = GitLabContext.sure(local.getShared());
this.cache = CacheBuilder.newBuilder()
.maximumSize(config.getCacheMaximumSize())
.expireAfterWrite(config.getCacheTimeSec(), TimeUnit.SECONDS)
.build(
new CacheLoader<String, GitlabProject>() {
@Override
public GitlabProject load(@NotNull String userId) throws Exception {
if (userId.isEmpty())
return GitlabAPI.connect(context.getGitLabUrl(), null).getProject(projectId);
final GitlabAPI api = context.connect();
final String tailUrl = GitlabProject.URL + "/" + projectId + "?sudo=" + userId;
return api.retrieve().to(tailUrl, GitlabProject.class);
}
}
);
}
@Override
protected boolean tryRefresh(LimiterConfig config) {
// rate limiter
this.rateLimiter = AdjustableRateLimiter.create(config.getRate().getMaxRate());
// concurrent limiter
this.semaphore = new AdjustableSemaphore(config.getConcurrent().getMaxPermit(), true);
// counter limiter
// request limiter
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
cacheBuilder.expireAfterWrite(config.getCounter().getTimeout(), TimeUnit.MILLISECONDS);
this.counter = cacheBuilder.build(CacheLoader.from(() -> new AtomicLong(0)));
// the refresh rateLimiter
rateLimiter.setRate(config.getRate().getRateUnit());
// the refresh semaphore
semaphore.setMaxPermits(config.getConcurrent().getMaxPermit());
return true;
}
@Override protected Map<String, Table> getTableMap() {
if (!discoverTables) {
return ImmutableMap.of();
}
if (tableMap == null) {
final DruidConnectionImpl connection = new DruidConnectionImpl(url, coordinatorUrl);
Set<String> tableNames = connection.tableNames();
tableMap = Maps.asMap(
ImmutableSet.copyOf(tableNames),
CacheBuilder.newBuilder()
.build(CacheLoader.from(name -> table(name, connection))));
}
return tableMap;
}
public CachingAsyncLeaderElector(AsyncLeaderElector<T> delegateLeaderElector, CacheConfig cacheConfig) {
super(delegateLeaderElector);
cache = CacheBuilder.newBuilder()
.maximumSize(cacheConfig.getSize())
.build(CacheLoader.from(super::getLeadership));
cacheUpdater = event -> {
Leadership<T> leadership = event.newLeadership();
cache.put(event.topic(), CompletableFuture.completedFuture(leadership));
};
statusListener = status -> {
if (status == PrimitiveState.SUSPENDED || status == PrimitiveState.CLOSED) {
cache.invalidateAll();
}
};
addListener(cacheUpdater);
addStateChangeListener(statusListener);
}
/**
* Initialize this TaskWriter with the specified context object.
*/
@SuppressWarnings("unchecked")
public void initialize(TaskWriterContext context) {
this.context = context;
this.parameter = (T) context.getWriterParameter();
this.handlers = CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends Record>, Handler>() {
@Override
public Handler load(Class<? extends Record> clazz) throws Exception {
Handler handler = getHandler(clazz);
if (handler == null) {
throw new RecordNotSupportException(clazz);
}
handler.initialize(context);
return handler;
}
});
}
/**
* Constructor to configure cache size.
*
* @param backingMap a distributed, strongly consistent map for backing
* @param cacheConfig the cache configuration
*/
public CachingAsyncAtomicMap(AsyncAtomicMap<K, V> backingMap, CacheConfig cacheConfig) {
super(backingMap);
this.backingMap = backingMap;
cache = CacheBuilder.newBuilder()
.maximumSize(cacheConfig.getSize())
.build(CacheLoader.from(CachingAsyncAtomicMap.super::get));
cacheUpdater = event -> {
Versioned<V> newValue = event.newValue();
if (newValue == null) {
cache.invalidate(event.key());
} else {
cache.put(event.key(), CompletableFuture.completedFuture(newValue));
}
mapEventListeners.forEach((listener, executor) -> executor.execute(() -> listener.event(event)));
};
statusListener = status -> {
log.debug("{} status changed to {}", this.name(), status);
// If the status of the underlying map is SUSPENDED or INACTIVE
// we can no longer guarantee that the cache will be in sync.
if (status == PrimitiveState.SUSPENDED || status == PrimitiveState.CLOSED) {
cache.invalidateAll();
}
};
super.addListener(cacheUpdater, MoreExecutors.directExecutor());
super.addStateChangeListener(statusListener);
}
private LoadingCache<String, FactTypeEntity> createFactTypeByNameCache() {
return CacheBuilder.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, FactTypeEntity>() {
@Override
public FactTypeEntity load(String key) throws Exception {
return ObjectUtils.notNull(factTypeDao.get(key), new Exception(String.format("FactType with name = %s does not exist.", key)));
}
});
}
private LoadingCache<String, ObjectTypeEntity> createObjectTypeByNameCache() {
return CacheBuilder.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, ObjectTypeEntity>() {
@Override
public ObjectTypeEntity load(String key) throws Exception {
return ObjectUtils.notNull(objectTypeDao.get(key), new Exception(String.format("ObjectType with name = %s does not exist.", key)));
}
});
}
/**
* The default query matching strategy for the 2016 evaluation.
*/
public static EREBasedCorpusQueryExecutor createDefaultFor2016(
final Map<Symbol, File> docIdToEREMap,
final ERELoader ereLoader, final EREToKBPEventOntologyMapper ontologyMapper,
int slack, double minNominalCASOverlap,
boolean requireBestCASType) {
final LoadingCache<Symbol, EREDocument> ereDocCache = CacheBuilder.newBuilder()
.maximumSize(50)
.build(new CacheLoader<Symbol, EREDocument>() {
@Override
public EREDocument load(final Symbol docID) throws Exception {
final File ereFileName = docIdToEREMap.get(docID);
if (ereFileName != null) {
return ereLoader.loadFrom(ereFileName);
} else {
throw new TACKBPEALException("Cannot find ERE file for " + docID);
}
}
});
final ResponsePJContainsEntryPJWithSlack commonPJMatchStrategy =
new ResponsePJContainsEntryPJWithSlack(slack);
final ImmutableList<AlignmentConfiguration> alignmentConfigs = ImmutableList.of(
AlignmentConfiguration.of(ExactCASMatch.INSTANCE, commonPJMatchStrategy),
AlignmentConfiguration.of(QueryNameContainsSystemCAS.INSTANCE, commonPJMatchStrategy),
AlignmentConfiguration.of(QueryNameContainedBySystemCAS.INSTANCE, commonPJMatchStrategy),
AlignmentConfiguration.of(
new NominalsContainOneAnotherWithMinimumOverlap(minNominalCASOverlap),
commonPJMatchStrategy));
return new EREBasedCorpusQueryExecutor(alignmentConfigs, ereDocCache, ontologyMapper,
requireBestCASType);
}
/**
* Required-args Constructor.
*
* @param sharedSecretBytesSupplier A {@link SharedSecretBytesSupplier} that returns a copy of the shared secret used
* to sign JWTs using the HS_256 algorithm.
* @param outgoingLinkSettings A {@link OutgoingLinkSettings} that contains all settings required to construct a
* bearer token that can auth an outgoing request.
*/
public JwtHs256BearerTokenSupplier(
final SharedSecretBytesSupplier sharedSecretBytesSupplier,
final OutgoingLinkSettings outgoingLinkSettings
) {
Objects.requireNonNull(sharedSecretBytesSupplier);
Objects.requireNonNull(outgoingLinkSettings);
this.outgoingLinkSettings = Objects.requireNonNull(outgoingLinkSettings);
ilpOverHttpAuthTokens = CacheBuilder.newBuilder()
// There should only ever be 1 or 2 tokens in-memory for a given client instance.
.maximumSize(3)
// Expire after this duration, which will correspond to the last incoming request from the peer.
.expireAfterAccess(getExpiryInMinutes(Duration.of(30, ChronoUnit.MINUTES)).toMinutes(), TimeUnit.MINUTES)
.removalListener((RemovalListener<String, String>) notification ->
logger.debug("Removing IlpOverHttp AuthToken from Cache for Principal: {}", notification.getKey())
)
.build(new CacheLoader<String, String>() {
public String load(final String authSubject) {
Objects.requireNonNull(authSubject);
final byte[] sharedSecretBytes = sharedSecretBytesSupplier.get();
try {
return JWT.create()
.withSubject(outgoingLinkSettings.jwtAuthSettings().get().tokenSubject()) // account identifier at the remote server.
// Expire at the appointed time, or else after 15 minutes.
.withExpiresAt(
Date.from(DateUtils.now().plus(getExpiryInMinutes(Duration.of(15, ChronoUnit.MINUTES))))
)
.sign(Algorithm.HMAC256(sharedSecretBytes));
} finally {
// Zero-out all bytes in the `sharedSecretBytes` array.
Arrays.fill(sharedSecretBytes, (byte) 0);
}
}
});
}
/**
* Creates a LoadingCache with default settings.
*
* @param loadingFunction loading function
* @param <K> key type
* @param <V> value type
* @return loading cache
*/
public static <K, V> LoadingCache<K, V> cache(Function<K, V> loadingFunction) {
return CacheBuilder.newBuilder()
.build(new CacheLoader<K, V>() {
@Override
public V load(K key) throws Exception {
return loadingFunction.apply(key);
}
});
}
@PostConstruct
protected void initCache() {
FlowableCommonAppProperties.Cache cache = properties.getCacheUsers();
long userCacheMaxSize = cache.getMaxSize();
long userCacheMaxAge = cache.getMaxAge();
userCache = CacheBuilder.newBuilder().maximumSize(userCacheMaxSize)
.expireAfterAccess(userCacheMaxAge, TimeUnit.SECONDS).recordStats().build(new CacheLoader<String, CachedUser>() {
public CachedUser load(final String userId) throws Exception {
User userFromDatabase = null;
if (ldapProperties == null || !ldapProperties.isEnabled()) {
userFromDatabase = identityService.createUserQuery().userIdIgnoreCase(userId.toLowerCase()).singleResult();
} else {
userFromDatabase = identityService.createUserQuery().userId(userId).singleResult();
}
if (userFromDatabase == null) {
throw new UsernameNotFoundException("User " + userId + " was not found in the database");
}
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
UserInformation userInformation = userService.getUserInformation(userFromDatabase.getId());
for (String privilege : userInformation.getPrivileges()) {
grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
}
return new CachedUser(userFromDatabase, grantedAuthorities);
}
});
}
public CachingJdbcClient(JdbcClient delegate, Duration metadataCachingTtl, boolean cacheMissing)
{
this.delegate = requireNonNull(delegate, "delegate is null");
this.cacheMissing = cacheMissing;
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
.expireAfterWrite(metadataCachingTtl.toMillis(), TimeUnit.MILLISECONDS);
schemaNamesCache = cacheBuilder.build(CacheLoader.from(delegate::getSchemaNames));
tableNamesCache = cacheBuilder.build(CacheLoader.from(key -> delegate.getTableNames(key.identity, key.schemaName)));
tableHandleCache = cacheBuilder.build(CacheLoader.from(key -> delegate.getTableHandle(key.identity, key.tableName)));
// TODO use LoadingCache for columns (columns depend on session and session cannot be used in cache key)
columnsCache = cacheBuilder.build();
}
public GuavaCacheProvider(long maximumSize) {
this.cache = CacheBuilder.newBuilder()
.maximumSize(maximumSize)
.build(
new CacheLoader<String, CacheEntry<T>>() {
@Override
public CacheEntry<T> load(String s) throws Exception {
return null;
}
}
);
}
public FileCache(FileFunction<T> fn, int cacheSize, int parallelism) {
this.fn = fn;
this.cache =
CacheBuilder.newBuilder()
.maximumSize(cacheSize)
.concurrencyLevel(parallelism)
.build(CacheLoader.from(CachedFile::new));
}
public static <K, V> ConcurrentMap<K, V> makeComputingMap(CacheBuilder<Object, Object> builder,
Function<? super K, ? extends V> computingFunction) {
final Function<? super K, ? extends V> function = computingFunction;
LoadingCache<K, V> computingCache = builder.build(new CacheLoader<K, V>() {
@Override
public V load(K key) throws Exception {
return function.apply(key);
}
});
return new MigrateConcurrentMap<K, V>(computingCache);
}