本文整理匯總了Java中com.google.common.cache.RemovalListener類的典型用法代碼示例。如果您正苦於以下問題:Java RemovalListener類的具體用法?Java RemovalListener怎麽用?Java RemovalListener使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
RemovalListener類屬於com.google.common.cache包,在下文中一共展示了RemovalListener類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: AccessTokenJob
import com.google.common.cache.RemovalListener; //導入依賴的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.RemovalListener; //導入依賴的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: KMSAudit
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
/**
* Create a new KMSAudit.
*
* @param windowMs Duplicate events within the aggregation window are quashed
* to reduce log traffic. A single message for aggregated
* events is printed at the end of the window, along with a
* count of the number of aggregated events.
*/
KMSAudit(long windowMs) {
cache = CacheBuilder.newBuilder()
.expireAfterWrite(windowMs, TimeUnit.MILLISECONDS)
.removalListener(
new RemovalListener<String, AuditEvent>() {
@Override
public void onRemoval(
RemovalNotification<String, AuditEvent> entry) {
AuditEvent event = entry.getValue();
if (event.getAccessCount().get() > 0) {
KMSAudit.this.logEvent(event);
event.getAccessCount().set(0);
KMSAudit.this.cache.put(entry.getKey(), event);
}
}
}).build();
executor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder()
.setDaemon(true).setNameFormat(KMS_LOGGER_NAME + "_thread").build());
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
cache.cleanUp();
}
}, windowMs / 10, windowMs / 10, TimeUnit.MILLISECONDS);
}
示例4: RENAudit
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
/**
* Create a new KMSAudit.
*
* @param windowMs Duplicate events within the aggregation window are quashed
* to reduce log traffic. A single message for aggregated
* events is printed at the end of the window, along with a
* count of the number of aggregated events.
*/
RENAudit(long windowMs) {
cache = CacheBuilder.newBuilder()
.expireAfterWrite(windowMs, TimeUnit.MILLISECONDS)
.removalListener(
new RemovalListener<String, AuditEvent>() {
@Override
public void onRemoval(
RemovalNotification<String, AuditEvent> entry) {
AuditEvent event = entry.getValue();
if (event.getAccessCount().get() > 0) {
RENAudit.this.logEvent(event);
event.getAccessCount().set(0);
RENAudit.this.cache.put(entry.getKey(), event);
}
}
}).build();
executor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder()
.setDaemon(true).setNameFormat(REN_LOGGER_NAME + "_thread").build());
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
cache.cleanUp();
}
}, windowMs / 10, windowMs / 10, TimeUnit.MILLISECONDS);
}
示例5: AuthorizationController
import com.google.common.cache.RemovalListener; //導入依賴的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);
}
});
}
示例6: KeyProviderCache
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
public KeyProviderCache(long expiryMs) {
cache = CacheBuilder.newBuilder()
.expireAfterAccess(expiryMs, TimeUnit.MILLISECONDS)
.removalListener(new RemovalListener<URI, KeyProvider>() {
@Override
public void onRemoval(
RemovalNotification<URI, KeyProvider> notification) {
try {
notification.getValue().close();
} catch (Throwable e) {
LOG.error(
"Error closing KeyProvider with uri ["
+ notification.getKey() + "]", e);
;
}
}
})
.build();
}
示例7: initExcludedNodes
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
private static LoadingCache<DatanodeInfo, DatanodeInfo> initExcludedNodes(
long excludedNodesCacheExpiry) {
return CacheBuilder.newBuilder()
.expireAfterWrite(excludedNodesCacheExpiry, TimeUnit.MILLISECONDS)
.removalListener(new RemovalListener<DatanodeInfo, DatanodeInfo>() {
@Override
public void onRemoval(
@Nonnull RemovalNotification<DatanodeInfo, DatanodeInfo>
notification) {
LOG.info("Removing node " + notification.getKey()
+ " from the excluded nodes list");
}
}).build(new CacheLoader<DatanodeInfo, DatanodeInfo>() {
@Override
public DatanodeInfo load(DatanodeInfo key) throws Exception {
return key;
}
});
}
示例8: createCache
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
/**
* Creates a {@link Cache} configured by this instance.
*
* @param <T>
* the type of the value stored in the Cache
* @param out
* a concurrent {@code Deque} to which the cached values are
* added as they are removed from the cache
* @param ticker
* the time source used to determine expiration
* @return a {@link Cache} corresponding to this instance's values or
* {@code null} unless {@code #numEntries} is positive.
*/
@Nullable
public <T> Cache<String, T> createCache(final ConcurrentLinkedDeque<T> out, Ticker ticker) {
Preconditions.checkNotNull(out, "The out deque cannot be null");
Preconditions.checkNotNull(ticker, "The ticker cannot be null");
if (numEntries <= 0) {
return null;
}
final RemovalListener<String, T> listener = new RemovalListener<String, T>() {
@Override
public void onRemoval(RemovalNotification<String, T> notification) {
out.addFirst(notification.getValue());
}
};
CacheBuilder<String, T> b = CacheBuilder.newBuilder().maximumSize(numEntries).ticker(ticker)
.removalListener(listener);
if (expirationMillis >= 0) {
b.expireAfterWrite(expirationMillis, TimeUnit.MILLISECONDS);
}
return b.build();
}
示例9: createCache
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
/**
* Creates a {@link Cache} configured by this instance.
*
* @param <T>
* the type of the value stored in the Cache
* @param out
* a concurrent {@code Deque} to which cached values are added as
* they are removed from the cache
* @param ticker
* the time source used to determine expiration
* @return a {@link Cache} corresponding to this instance's values or
* {@code null} unless {@code #numEntries} is positive.
*/
@Nullable
public <T> Cache<String, T> createCache(final ConcurrentLinkedDeque<T> out, Ticker ticker) {
Preconditions.checkNotNull(out, "The out deque cannot be null");
Preconditions.checkNotNull(ticker, "The ticker cannot be null");
if (numEntries <= 0) {
return null;
}
final RemovalListener<String, T> listener = new RemovalListener<String, T>() {
@Override
public void onRemoval(RemovalNotification<String, T> notification) {
out.addFirst(notification.getValue());
}
};
CacheBuilder<String, T> b = CacheBuilder.newBuilder().maximumSize(numEntries).ticker(ticker)
.removalListener(listener);
if (flushCacheEntryIntervalMillis >= 0) {
b.expireAfterWrite(flushCacheEntryIntervalMillis, TimeUnit.MILLISECONDS);
}
return b.build();
}
示例10: CircuitBreakerRegistryImpl
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
CircuitBreakerRegistryImpl(Vertx vertx, CircuitBreakerRegistryOptions options) {
this.vertx = vertx;
this.options = options;
this.cache = CacheBuilder.newBuilder()
.expireAfterAccess(options.getCacheExpires(), TimeUnit.SECONDS)
.removalListener(new RemovalListener<String, CircuitBreaker>() {
@Override
public void onRemoval(RemovalNotification<String, CircuitBreaker> notification) {
Log.create(LOGGER)
.setLogType(LogType.LOG)
.setModule("CircuitBreaker")
.setEvent("cache.removed")
.addData("key", notification.getKey())
.setMessage("cause by: {}")
.addArg(notification.getCause())
.info();
}
})
.build(new CacheLoader<String, CircuitBreaker>() {
@Override
public CircuitBreaker load(String circuitBreakerName) throws Exception {
return create(circuitBreakerName);
}
});
}
示例11: ZKDiscoveryService
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
/**
* Constructs ZKDiscoveryService using the provided zookeeper client for storing service registry under namespace.
* @param zkClient of zookeeper quorum
* @param namespace under which the service registered would be stored in zookeeper.
* If namespace is {@code null}, no namespace will be used.
*/
public ZKDiscoveryService(ZKClient zkClient, String namespace) {
this.closed = new AtomicBoolean();
this.discoverables = HashMultimap.create();
this.lock = new ReentrantLock();
this.retryExecutor = Executors.newSingleThreadScheduledExecutor(
Threads.createDaemonThreadFactory("zk-discovery-retry"));
this.zkClient = namespace == null ? zkClient : ZKClients.namespace(zkClient, namespace);
this.services = CacheBuilder.newBuilder()
.removalListener(new RemovalListener<String, ServiceDiscoveredCacheEntry>() {
@Override
public void onRemoval(RemovalNotification<String, ServiceDiscoveredCacheEntry> notification) {
ServiceDiscoveredCacheEntry entry = notification.getValue();
if (entry != null) {
entry.cancel();
}
}
})
.build(createServiceLoader());
this.watcherCancellable = this.zkClient.addConnectionWatcher(createConnectionWatcher());
}
示例12: JmxConnectionCache
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
public JmxConnectionCache( int pollRateMs ) {
cache = CacheBuilder.newBuilder().expireAfterAccess( pollRateMs * 3, TimeUnit.MILLISECONDS ).removalListener(
new RemovalListener<VirtualMachineConnector, JmxConnection>() {
@Override
public void onRemoval( RemovalNotification<VirtualMachineConnector, JmxConnection> notification ) {
try {
if( notification.getValue() != null ) {
logger.info( "Removing idle connection to {}", notification.getKey() );
notification.getValue().getConnector().close();
}
} catch( IOException e ) {
logger.error( "Error closing connection to {}", notification.getKey(), e );
}
}
} ).build( new CacheLoader<VirtualMachineConnector, JmxConnection>() {
@Override
public JmxConnection load( VirtualMachineConnector key ) throws Exception {
return key.connect();
}
} );
}
示例13: testCacheExpire
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
@Test
public void testCacheExpire() throws InterruptedException {
int total = 10;
final Map<String, String> expired = new HashMap<>();
RemovalListener removalListener = new RemovalListener<String, String>() {
@Override
public void onRemoval(RemovalNotification<String, String> notification) {
if(RemovalCause.EXPIRED == notification.getCause()) {
expired.put(notification.getKey(), notification.getValue());
}
}
};
Cache<String, String> myCache = CacheBuilder.newBuilder()
.expireAfterWrite(2, TimeUnit.MILLISECONDS)
.removalListener(removalListener)
.build();
for(int i = 0; i < total; i++) {
myCache.put("key_" + i, "val_" + i);
}
Thread.sleep(10);
myCache.cleanUp();
assertEquals(total, expired.size());
}
示例14: AutoScaleProcessor
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
AutoScaleProcessor(AutoScalerConfig configuration,
ScheduledExecutorService maintenanceExecutor) {
this.configuration = configuration;
this.maintenanceExecutor = maintenanceExecutor;
serializer = new JavaSerializer<>();
writerConfig = EventWriterConfig.builder().build();
writer = new AtomicReference<>();
cache = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CAPACITY)
.maximumSize(MAX_CACHE_SIZE)
.expireAfterAccess(configuration.getCacheExpiry().getSeconds(), TimeUnit.SECONDS)
.removalListener(RemovalListeners.asynchronous((RemovalListener<String, Pair<Long, Long>>) notification -> {
if (notification.getCause().equals(RemovalCause.EXPIRED)) {
triggerScaleDown(notification.getKey(), true);
}
}, maintenanceExecutor))
.build();
CompletableFuture.runAsync(this::bootstrapRequestWriters, maintenanceExecutor);
}
示例15: init
import com.google.common.cache.RemovalListener; //導入依賴的package包/類
private LoadingCache<Map.Entry<Integer, KeyType>, ValueType> init(final CacheConfig cacheConfig, final RemovalListener removalListener) {
CacheBuilder builder = CacheBuilder.newBuilder()
.expireAfterWrite(cacheConfig.getDuration(), cacheConfig.getTimeUnit());
if (removalListener != null) {
builder = builder.removalListener(removalListener);
}
final CacheLoader<Map.Entry<Integer, KeyType>, ValueType> loader = new CacheLoader<Map.Entry<Integer, KeyType>, ValueType>() {
@Override
public ValueType load(Map.Entry<Integer, KeyType> params) throws Exception {
return loadNewEntry(params.getKey(), params.getValue());
}
};
return builder.build(loader);
}