Java Code Examples for com.github.benmanes.caffeine.cache.Caffeine#newBuilder()

The following examples show how to use com.github.benmanes.caffeine.cache.Caffeine#newBuilder() . 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: CaffeineProvider.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
/**
 * 返回对 Caffeine cache 的 封装
 * @param region region name
 * @param size   max cache object size in memory
 * @param expire cache object expire time in millisecond
 *               if this parameter set to 0 or negative numbers
 *               means never expire
 * @param listener  j2cache cache listener
 * @return CaffeineCache
 */
private CaffeineCache newCaffeineCache(String region, long size, long expire, CacheExpiredListener listener) {
    Caffeine<Object, Object> caffeine = Caffeine.newBuilder();
    caffeine = caffeine.maximumSize(size)
        .removalListener((k,v, cause) -> {
            /*
             * 程序删除的缓存不做通知处理,因为上层已经做了处理
             * 当缓存数据不是因为手工删除和超出容量限制而被删除的情况,就需要通知上层侦听器
             */
            if(cause != RemovalCause.EXPLICIT && cause != RemovalCause.REPLACED && cause != RemovalCause.SIZE)
                listener.notifyElementExpired(region, (String)k);
        });
    if (expire > 0) {
        caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS);
    }
    com.github.benmanes.caffeine.cache.Cache<String, Object> loadingCache = caffeine.build();
    return new CaffeineCache(loadingCache, size, expire);
}
 
Example 2
Source File: AuthCache.java    From timely with Apache License 2.0 6 votes vote down vote up
private static Cache<String, TimelyPrincipal> getCache() {
    if (-1 == cacheExpirationMinutes) {
        throw new IllegalStateException("Cache session max age not configured.");
    }
    if (null == CACHE) {
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder();
        caffeine.expireAfterWrite(cacheExpirationMinutes, TimeUnit.MINUTES);
        if (cacheRefreshMinutes > 0) {
            caffeine.refreshAfterWrite(cacheRefreshMinutes, TimeUnit.MINUTES);
            CACHE = caffeine.build(key -> getTimelyPrincipal(key));
        } else {
            CACHE = caffeine.build();
        }
    }
    return CACHE;
}
 
Example 3
Source File: ToolsCacheManager.java    From tools with MIT License 6 votes vote down vote up
/**
 * 构建caffeine缓存
 *
 * @return caffeine cache
 */
private com.github.benmanes.caffeine.cache.Cache<Object, Object> caffeineCache() {
    com.github.benmanes.caffeine.cache.Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder();
    if (caffeineCache.getExpireAfterAccess() > 0) {
        cacheBuilder.expireAfterAccess(caffeineCache.getExpireAfterAccess(), TimeUnit.MILLISECONDS);
    }
    if (caffeineCache.getExpireAfterWrite() > 0) {
        cacheBuilder.expireAfterWrite(caffeineCache.getExpireAfterWrite(), TimeUnit.MILLISECONDS);
    }
    if (caffeineCache.getInitialCapacity() > 0) {
        cacheBuilder.initialCapacity(caffeineCache.getInitialCapacity());
    }
    if (caffeineCache.getMaximumSize() > 0) {
        cacheBuilder.maximumSize(caffeineCache.getMaximumSize());
    }
    if (caffeineCache.getRefreshAfterWrite() > 0) {
        cacheBuilder.refreshAfterWrite(caffeineCache.getRefreshAfterWrite(), TimeUnit.MILLISECONDS);
    }
    return cacheBuilder.build();
}
 
Example 4
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testMaximumSize_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.maximumSize(-1);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 5
Source File: CacheFactory.java    From caffeine with Apache License 2.0 5 votes vote down vote up
Builder(CacheManager cacheManager, String cacheName, CaffeineConfiguration<K, V> config) {
  this.config = config;
  this.cacheName = cacheName;
  this.cacheManager = cacheManager;
  this.caffeine = Caffeine.newBuilder();
  this.statistics = new JCacheStatisticsMXBean();
  this.ticker = config.getTickerFactory().create();
  this.executor = config.getExecutorFactory().create();
  this.expiryPolicy = config.getExpiryPolicyFactory().create();
  this.dispatcher = new EventDispatcher<>(executor);

  caffeine.ticker(ticker);
  caffeine.executor(executor);
  config.getCacheEntryListenerConfigurations().forEach(dispatcher::register);
}
 
Example 6
Source File: LocalCacheListener.java    From redisson with Apache License 2.0 5 votes vote down vote up
public ConcurrentMap<CacheKey, CacheValue> createCache(LocalCachedMapOptions<?, ?> options) {
    if (options.getCacheProvider() == LocalCachedMapOptions.CacheProvider.CAFFEINE) {
        Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder();
        if (options.getTimeToLiveInMillis() > 0) {
            caffeineBuilder.expireAfterWrite(options.getTimeToLiveInMillis(), TimeUnit.MILLISECONDS);
        }
        if (options.getMaxIdleInMillis() > 0) {
            caffeineBuilder.expireAfterAccess(options.getMaxIdleInMillis(), TimeUnit.MILLISECONDS);
        }
        if (options.getCacheSize() > 0) {
            caffeineBuilder.maximumSize(options.getCacheSize());
        }
        if (options.getEvictionPolicy() == LocalCachedMapOptions.EvictionPolicy.SOFT) {
            caffeineBuilder.softValues();
        }
        if (options.getEvictionPolicy() == LocalCachedMapOptions.EvictionPolicy.WEAK) {
            caffeineBuilder.weakValues();
        }
        return caffeineBuilder.<CacheKey, CacheValue>build().asMap();
    }

    if (options.getEvictionPolicy() == EvictionPolicy.NONE) {
        return new NoneCacheMap<>(options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.LRU) {
        return new LRUCacheMap<>(options.getCacheSize(), options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.LFU) {
        return new LFUCacheMap<>(options.getCacheSize(), options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.SOFT) {
        return ReferenceCacheMap.soft(options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.WEAK) {
        return ReferenceCacheMap.weak(options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    throw new IllegalArgumentException("Invalid eviction policy: " + options.getEvictionPolicy());
}
 
Example 7
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@GwtIncompatible // java.time.Duration
public void testRefresh_zero_duration() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.refreshAfterWrite(java.time.Duration.ZERO);
    fail();
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 8
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@GwtIncompatible("refreshAfterWrite")
public void testRefresh_zero() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.refreshAfterWrite(0, SECONDS);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 9
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@GwtIncompatible // java.time.Duration
public void testTimeToIdle_negative_duration() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.expireAfterAccess(java.time.Duration.ofSeconds(-1));
    fail();
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 10
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testTimeToIdle_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.expireAfterAccess(-1, SECONDS);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 11
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@GwtIncompatible // java.time.Duration
public void testTimeToLive_negative_duration() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.expireAfterWrite(java.time.Duration.ofSeconds(-1));
    fail();
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 12
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testTimeToLive_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.expireAfterWrite(-1, SECONDS);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 13
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@GwtIncompatible("maximumWeight")
public void testMaximumWeight_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.maximumWeight(-1);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 14
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testInitialCapacity_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.initialCapacity(-1);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 15
Source File: CacheBuilderFactory.java    From caffeine with Apache License 2.0 5 votes vote down vote up
private Caffeine<Object, Object> createCacheBuilder(
    Integer concurrencyLevel, Integer initialCapacity, Integer maximumSize,
    DurationSpec expireAfterWrite, DurationSpec expireAfterAccess, DurationSpec refresh,
    Strength keyStrength, Strength valueStrength) {

  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  if (concurrencyLevel != null) {
    //builder.concurrencyLevel(concurrencyLevel);
  }
  if (initialCapacity != null) {
    builder.initialCapacity(initialCapacity);
  }
  if (maximumSize != null) {
    builder.maximumSize(maximumSize);
  }
  if (expireAfterWrite != null) {
    builder.expireAfterWrite(expireAfterWrite.duration, expireAfterWrite.unit);
  }
  if (expireAfterAccess != null) {
    builder.expireAfterAccess(expireAfterAccess.duration, expireAfterAccess.unit);
  }
  if (refresh != null) {
    builder.refreshAfterWrite(refresh.duration, refresh.unit);
  }
  if (keyStrength == Strength.WEAK) {
    builder.weakKeys();
  }
  if (valueStrength == Strength.WEAK) {
    builder.weakValues();
  } else if (valueStrength == Strength.SOFT) {
    builder.softValues();
  }
  builder.executor(MoreExecutors.directExecutor());
  return builder;
}
 
Example 16
Source File: ParsecAsyncHttpResponseLoadingCache.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param client client
 */
public Builder(final ParsecAsyncHttpClient client) {
    caffeine = Caffeine.newBuilder();
    this.client = client;
    cleanUpInterval = DEFAULT_CLEANUP_INTERVAL;
    cleanUpTimeUnit = TimeUnit.SECONDS;
}
 
Example 17
Source File: DittoMongoCollectionCache.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
public DittoMongoCollectionCache(final Config config) {
    final String ttl = "expire-after-write";
    final String maxSize = "max-size";

    final Caffeine<Object, Object> caffeine = Caffeine.newBuilder();
    tryLookup(ttl, config::getDuration).ifPresent(caffeine::expireAfterWrite);
    tryLookup(maxSize, config::getLong).ifPresent(caffeine::maximumSize);
    cache = CaffeineCache.of(caffeine);
}
 
Example 18
Source File: CaffeineCache.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public CaffeineCache(String name, int capacity, Mapper<K, V> loader, long ttl, boolean statistics, boolean manageable) {
	this.name = name;
	this.capacity = capacity;
	this.ttl = ttl;
	this.loading = loader != null;

	Caffeine<Object, Object> builder = Caffeine.newBuilder();

	if (capacity > 0) {
		builder.maximumSize(capacity);
	}

	if (ttl > 0) {
		builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
	}

	if (statistics) {
		builder.recordStats();
	}

	if (manageable) {
		new ManageableCache(this);
	}

	if (loading) {
		this.loadingCache = builder.build(loader::map);
		this.cache = loadingCache;

	} else {
		this.loadingCache = null;
		this.cache = builder.build();
	}
}
 
Example 19
Source File: CaffeineCacheFactory.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Cache<K, V> build(final String name, final CacheConfig<K, V> config) {
    Caffeine<Object, Object> builder = Caffeine.newBuilder();
    if (config.getExpireAfterWrite() > 0) {
        builder.expireAfterWrite(config.getExpireAfterWrite(), TimeUnit.MILLISECONDS);
    }
    builder.maximumSize(config.getCapacity() > 0 ? config.getCapacity() : Long.MAX_VALUE);
    com.github.benmanes.caffeine.cache.Cache<K, CacheObject<V>> cache = builder.build();
    return new CaffeineCache<>(cache, config);
}
 
Example 20
Source File: CaffeineCacheFromContext.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public static <K, V> Cache<K, V> newCaffeineCache(CacheContext context) {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  context.caffeine = builder;

  if (context.initialCapacity != InitialCapacity.DEFAULT) {
    builder.initialCapacity(context.initialCapacity.size());
  }
  if (context.isRecordingStats()) {
    builder.recordStats();
  }
  if (context.maximumSize != Maximum.DISABLED) {
    if (context.weigher == CacheWeigher.DEFAULT) {
      builder.maximumSize(context.maximumSize.max());
    } else {
      builder.weigher(context.weigher);
      builder.maximumWeight(context.maximumWeight());
    }
  }
  if (context.expiryType() != CacheExpiry.DISABLED) {
    builder.expireAfter(context.expiry);
  }
  if (context.afterAccess != Expire.DISABLED) {
    builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS);
  }
  if (context.afterWrite != Expire.DISABLED) {
    builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS);
  }
  if (context.refresh != Expire.DISABLED) {
    builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS);
  }
  if (context.expires() || context.refreshes()) {
    SerializableTicker ticker = context.ticker()::read;
    builder.ticker(ticker);
  }
  if (context.keyStrength == ReferenceType.WEAK) {
    builder.weakKeys();
  } else if (context.keyStrength == ReferenceType.SOFT) {
    throw new IllegalStateException();
  }
  if (context.isWeakValues()) {
    builder.weakValues();
  } else if (context.isSoftValues()) {
    builder.softValues();
  }
  if (context.cacheExecutor != CacheExecutor.DEFAULT) {
    builder.executor(context.executor);
  }
  if (context.cacheScheduler != CacheScheduler.DEFAULT) {
    builder.scheduler(context.scheduler);
  }
  if (context.removalListenerType != Listener.DEFAULT) {
    builder.removalListener(context.removalListener);
  }
  if (context.isStrongKeys() && !context.isAsync()) {
    builder.writer(context.cacheWriter());
  }
  if (context.isAsync()) {
    if (context.loader == null) {
      context.asyncCache = builder.buildAsync();
    } else {
      context.asyncCache = builder.buildAsync(
          context.isAsyncLoading ? context.loader.async() : context.loader);
    }
    context.cache = context.asyncCache.synchronous();
  } else if (context.loader == null) {
    context.cache = builder.build();
  } else {
    context.cache = builder.build(context.loader);
  }

  @SuppressWarnings("unchecked")
  Cache<K, V> castedCache = (Cache<K, V>) context.cache;
  RandomSeedEnforcer.resetThreadLocalRandom();
  return castedCache;
}