com.github.benmanes.caffeine.cache.AsyncCacheLoader Java Examples

The following examples show how to use com.github.benmanes.caffeine.cache.AsyncCacheLoader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CaffeineCache.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CaffeineCache(final Caffeine<? super K, ? super V> caffeine,
        final AsyncCacheLoader<K, V> loader,
        @Nullable final String cacheName) {

    if (cacheName != null) {
        this.metricStatsCounter =
                MetricsStatsCounter.of(cacheName, this::getMaxCacheSize, this::getCurrentCacheSize);
        caffeine.recordStats(() -> metricStatsCounter);
        this.asyncLoadingCache = caffeine.buildAsync(loader);
        this.synchronousCacheView = asyncLoadingCache.synchronous();
    } else {
        this.asyncLoadingCache = caffeine.buildAsync(loader);
        this.synchronousCacheView = asyncLoadingCache.synchronous();
        this.metricStatsCounter = null;
    }
}
 
Example #2
Source File: DittoPublicKeyProvider.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private DittoPublicKeyProvider(final JwtSubjectIssuersConfig jwtSubjectIssuersConfig,
        final HttpClientFacade httpClient,
        final CacheConfig publicKeysConfig,
        final String cacheName) {

    this.jwtSubjectIssuersConfig = argumentNotNull(jwtSubjectIssuersConfig);
    this.httpClient = argumentNotNull(httpClient);
    argumentNotNull(publicKeysConfig, "config of the public keys cache");
    argumentNotNull(cacheName);

    final AsyncCacheLoader<PublicKeyIdWithIssuer, PublicKey> loader = this::loadPublicKey;

    final Caffeine<PublicKeyIdWithIssuer, PublicKey> caffeine = Caffeine.newBuilder()
            .maximumSize(publicKeysConfig.getMaximumSize())
            .expireAfterWrite(publicKeysConfig.getExpireAfterWrite())
            .removalListener(new CacheRemovalListener());

    publicKeyCache = CaffeineCache.of(caffeine, loader, cacheName);
}
 
Example #3
Source File: EnforcementFlow.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create an EnforcementFlow object.
 *
 * @param updaterStreamConfig configuration of the updater stream.
 * @param thingsShardRegion the shard region to retrieve things from.
 * @param policiesShardRegion the shard region to retrieve policies from.
 * @param cacheDispatcher dispatcher for the enforcer cache.
 * @return an EnforcementFlow object.
 */
public static EnforcementFlow of(final StreamConfig updaterStreamConfig,
        final ActorRef thingsShardRegion,
        final ActorRef policiesShardRegion,
        final MessageDispatcher cacheDispatcher,
        final boolean deleteEvent) {

    final Duration askTimeout = updaterStreamConfig.getAskTimeout();
    final StreamCacheConfig streamCacheConfig = updaterStreamConfig.getCacheConfig();

    final AsyncCacheLoader<EntityIdWithResourceType, Entry<Enforcer>> policyEnforcerCacheLoader =
            new PolicyEnforcerCacheLoader(askTimeout, policiesShardRegion);
    final Cache<EntityIdWithResourceType, Entry<Enforcer>> policyEnforcerCache =
            CacheFactory.createCache(policyEnforcerCacheLoader, streamCacheConfig,
                    EnforcementFlow.class.getCanonicalName() + ".cache", cacheDispatcher);

    return new EnforcementFlow(thingsShardRegion, policyEnforcerCache, askTimeout,
            streamCacheConfig.getRetryDelay(), updaterStreamConfig.getMaxArraySize(), deleteEvent);
}
 
Example #4
Source File: TitusClientImpl.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private AsyncLoadingCache<String, Job> buildCacheForJobs() {
    return Caffeine.newBuilder()
            .maximumSize(MAX_CACHE_SIZE)
            .buildAsync(new AsyncCacheLoader<String, Job>() {
                @Nonnull
                @Override
                public CompletableFuture<Job> asyncLoad(@Nonnull String jobId, @Nonnull Executor executor) {
                    ListenableFuture<Job> jobFuture = jobManagementServiceFutureStub.findJob(JobId.newBuilder().setId(jobId).build());
                    return toCompletableFuture(jobFuture, executor);
                }
            });
}
 
Example #5
Source File: CaffeineTest.java    From cache2k-benchmark with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncLoader() throws Exception {
	AsyncLoadingCache c =
	Caffeine.newBuilder()
		.buildAsync(new AsyncCacheLoader<Object, Object>() {
			@Override
			public CompletableFuture<Object> asyncLoad(final Object key, final Executor executor) {
				return CompletableFuture.completedFuture("okay");
			}
		});
	CompletableFuture<Map> cf = c.getAll(Arrays.asList(1, 2, 3));
	Map m = cf.get();
}
 
Example #6
Source File: DefaultEnforcerActorFactory.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public ActorRef startEnforcerActor(final ActorContext context, final ConciergeConfig conciergeConfig,
        final ActorRef pubSubMediator, final ShardRegions shardRegions) {

    final CachesConfig cachesConfig = conciergeConfig.getCachesConfig();
    final Duration askTimeout = cachesConfig.getAskTimeout();
    final ActorSystem actorSystem = context.system();

    final ActorRef policiesShardRegionProxy = shardRegions.policies();

    final ActorRef thingsShardRegionProxy = shardRegions.things();

    final AsyncCacheLoader<EntityIdWithResourceType, Entry<EntityIdWithResourceType>> thingEnforcerIdCacheLoader =
            new ThingEnforcementIdCacheLoader(askTimeout, thingsShardRegionProxy);
    final Cache<EntityIdWithResourceType, Entry<EntityIdWithResourceType>> thingIdCache =
            CacheFactory.createCache(thingEnforcerIdCacheLoader, cachesConfig.getIdCacheConfig(),
                    ID_CACHE_METRIC_NAME_PREFIX + ThingCommand.RESOURCE_TYPE,
                    actorSystem.dispatchers().lookup("thing-id-cache-dispatcher"));

    final AsyncCacheLoader<EntityIdWithResourceType, Entry<Enforcer>> policyEnforcerCacheLoader =
            new PolicyEnforcerCacheLoader(askTimeout, policiesShardRegionProxy);
    final Cache<EntityIdWithResourceType, Entry<Enforcer>> policyEnforcerCache =
            CacheFactory.createCache(policyEnforcerCacheLoader, cachesConfig.getEnforcerCacheConfig(),
                    ENFORCER_CACHE_METRIC_NAME_PREFIX + "policy",
                    actorSystem.dispatchers().lookup("policy-enforcer-cache-dispatcher"));

    final AsyncCacheLoader<EntityIdWithResourceType, Entry<Enforcer>> aclEnforcerCacheLoader =
            new AclEnforcerCacheLoader(askTimeout, thingsShardRegionProxy);
    final Cache<EntityIdWithResourceType, Entry<Enforcer>> aclEnforcerCache =
            CacheFactory.createCache(aclEnforcerCacheLoader, cachesConfig.getEnforcerCacheConfig(),
                    ENFORCER_CACHE_METRIC_NAME_PREFIX + "acl",
                    actorSystem.dispatchers().lookup("acl-enforcer-cache-dispatcher"));

    // pre-enforcer
    final BlockedNamespaces blockedNamespaces = BlockedNamespaces.of(actorSystem);
    final PreEnforcer preEnforcer = newPreEnforcer(blockedNamespaces, PlaceholderSubstitution.newInstance());

    final LiveSignalPub liveSignalPub = LiveSignalPub.of(context);

    final Set<EnforcementProvider<?>> enforcementProviders = new HashSet<>();
    enforcementProviders.add(new ThingCommandEnforcement.Provider(thingsShardRegionProxy,
            policiesShardRegionProxy, thingIdCache, policyEnforcerCache, aclEnforcerCache, preEnforcer));
    enforcementProviders.add(new PolicyCommandEnforcement.Provider(policiesShardRegionProxy, policyEnforcerCache));
    enforcementProviders.add(new LiveSignalEnforcement.Provider(thingIdCache, policyEnforcerCache,
            aclEnforcerCache, liveSignalPub));

    final ActorRef conciergeEnforcerRouter =
            ConciergeEnforcerClusterRouterFactory.createConciergeEnforcerClusterRouter(context,
                    conciergeConfig.getClusterConfig().getNumberOfShards());

    context.actorOf(DispatcherActor.props(pubSubMediator, conciergeEnforcerRouter),
            DispatcherActor.ACTOR_NAME);

    final ActorRef conciergeForwarder =
            context.actorOf(ConciergeForwarderActor.props(pubSubMediator, conciergeEnforcerRouter),
                    ConciergeForwarderActor.ACTOR_NAME);
    pubSubMediator.tell(DistPubSubAccess.put(conciergeForwarder), ActorRef.noSender());

    // start cache invalidator
    final Props cachedNamespaceInvalidatorProps =
            CachedNamespaceInvalidator.props(blockedNamespaces,
                    Arrays.asList(thingIdCache, policyEnforcerCache, aclEnforcerCache));
    context.actorOf(cachedNamespaceInvalidatorProps, CachedNamespaceInvalidator.ACTOR_NAME);

    // start cluster singleton that writes to the distributed cache of blocked namespaces
    final Props blockedNamespacesUpdaterProps = BlockedNamespacesUpdater.props(blockedNamespaces, pubSubMediator);
    ClusterUtil.startSingleton(actorSystem, actorSystem, CLUSTER_ROLE,
            ConciergeMessagingConstants.BLOCKED_NAMESPACES_UPDATER_NAME,
            blockedNamespacesUpdaterProps);

    final Props enforcerProps =
            EnforcerActor.props(pubSubMediator, enforcementProviders, conciergeForwarder,
                    preEnforcer, thingIdCache, aclEnforcerCache,
                    policyEnforcerCache); // passes in the caches to be able to invalidate cache entries

    return context.actorOf(enforcerProps, EnforcerActor.ACTOR_NAME);
}
 
Example #7
Source File: PolicyCommandEnforcementTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static <K, V> CaffeineCache<K, V> createCache(final AsyncCacheLoader<K, V> loader) {
    return CaffeineCache.of(Caffeine.newBuilder(), loader);
}
 
Example #8
Source File: CaffeineCache.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static <K, V> AsyncCacheLoader<K, V> getTypedNullCacheLoader() {
    @SuppressWarnings("unchecked") final AsyncCacheLoader<K, V> nullCacheLoader =
            (AsyncCacheLoader<K, V>) NULL_CACHE_LOADER;
    return nullCacheLoader;
}
 
Example #9
Source File: MetricsStatsCounterTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private CaffeineCache<Integer, Integer> createCaffeineCache() {
    final Caffeine<Object, Object> caffeine = Caffeine.newBuilder().maximumSize(MAXIMUM_SIZE);
    final AsyncCacheLoader<Integer, Integer> loader = (key, executor) -> CompletableFuture.completedFuture(key);

    return CaffeineCache.of(caffeine, loader, TEST_CACHE_NAME);
}
 
Example #10
Source File: CacheContext.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public <K, V> AsyncLoadingCache<K, V> buildAsync(AsyncCacheLoader<K, V> loader) {
  checkState(isCaffeine() && isAsync());
  AsyncLoadingCache<K, V> cache = caffeine.buildAsync(loader);
  this.cache = cache.synchronous();
  return cache;
}
 
Example #11
Source File: CacheFactory.java    From ditto with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a cache.
 *
 * @param cacheLoader the cache loader.
 * @param cacheConfig the the cache's configuration.
 * @param cacheName the name of the cache or {@code null} if metrics should be disabled. Used as metric label.
 * @param executor the executor to use in the cache.
 * @param <K> the type of the cache keys.
 * @param <V> the type of the cache values.
 * @return the created cache.
 * @throws NullPointerException if any argument is {@code null}.
 */
public static <K, V> Cache<K, V> createCache(final AsyncCacheLoader<K, V> cacheLoader,
        final CacheConfig cacheConfig,
        @Nullable final String cacheName,
        final Executor executor) {

    checkNotNull(cacheLoader, "AsyncCacheLoader");

    return CaffeineCache.of(caffeine(cacheConfig, executor), cacheLoader, cacheName);
}
 
Example #12
Source File: CaffeineCache.java    From ditto with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new instance based on a {@link AsyncCacheLoader}.
 *
 * @param caffeine a (pre-configured) caffeine instance.
 * @param asyncLoader the algorithm used for loading values asynchronously.
 * @param <K> the type of the key.
 * @param <V> the type of the value.
 * @return the created instance
 */
public static <K, V> CaffeineCache<K, V> of(final Caffeine<? super K, ? super V> caffeine,
        final AsyncCacheLoader<K, V> asyncLoader) {
    requireNonNull(caffeine);
    requireNonNull(asyncLoader);

    return new CaffeineCache<>(caffeine, asyncLoader, null);
}
 
Example #13
Source File: CaffeineCache.java    From ditto with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new instance based with a Null-Cache-Loader. This is useful if the cache is populated manually.
 *
 * @param caffeine a (pre-configured) caffeine instance.
 * @param <K> the type of the key.
 * @param <V> the type of the value.
 * @return the created instance
 */
public static <K, V> CaffeineCache<K, V> of(final Caffeine<? super K, ? super V> caffeine) {
    requireNonNull(caffeine);

    final AsyncCacheLoader<K, V> cacheLoader = getTypedNullCacheLoader();
    return new CaffeineCache<>(caffeine, cacheLoader, null);
}
 
Example #14
Source File: CaffeineCache.java    From ditto with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new instance based with a Null-Cache-Loader. This is useful if the cache is populated manually.
 *
 * @param caffeine a (pre-configured) caffeine instance.
 * @param cacheName The name of the cache {@code null}. Will be used for metrics.
 * @param <K> the type of the key.
 * @param <V> the type of the value.
 * @return the created instance
 */
public static <K, V> CaffeineCache<K, V> of(final Caffeine<? super K, ? super V> caffeine,
        @Nullable final String cacheName) {
    requireNonNull(caffeine);

    final AsyncCacheLoader<K, V> cacheLoader = getTypedNullCacheLoader();
    return new CaffeineCache<>(caffeine, cacheLoader, cacheName);
}
 
Example #15
Source File: CaffeineCache.java    From ditto with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new instance based on a {@link AsyncCacheLoader} which may report metrics for cache statistics.
 *
 * @param caffeine a (pre-configured) caffeine instance.
 * @param loader the algorithm used for loading values asynchronously.
 * @param cacheName The name of the cache or {@code null} if metrics should be disabled. Will be used for metrics.
 * @param <K> the type of the key.
 * @param <V> the type of the value.
 * @return the created instance
 */
public static <K, V> CaffeineCache<K, V> of(final Caffeine<? super K, ? super V> caffeine,
        final AsyncCacheLoader<K, V> loader,
        @Nullable final String cacheName) {
    requireNonNull(caffeine);
    requireNonNull(loader);

    return new CaffeineCache<>(caffeine, loader, cacheName);
}