當前位置: 首頁>>代碼示例>>Java>>正文


Java RemovalNotification類代碼示例

本文整理匯總了Java中com.google.common.cache.RemovalNotification的典型用法代碼示例。如果您正苦於以下問題:Java RemovalNotification類的具體用法?Java RemovalNotification怎麽用?Java RemovalNotification使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


RemovalNotification類屬於com.google.common.cache包,在下文中一共展示了RemovalNotification類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: AccessTokenJob

import com.google.common.cache.RemovalNotification; //導入依賴的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();
				}
			});
}
 
開發者ID:tojaoomy,項目名稱:private-WeChat,代碼行數:25,代碼來源:AccessTokenJob.java

示例2: KMSAudit

import com.google.common.cache.RemovalNotification; //導入依賴的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);
}
 
開發者ID:nucypher,項目名稱:hadoop-oss,代碼行數:34,代碼來源:KMSAudit.java

示例3: RENAudit

import com.google.common.cache.RemovalNotification; //導入依賴的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);
}
 
開發者ID:nucypher,項目名稱:hadoop-oss,代碼行數:34,代碼來源:RENAudit.java

示例4: AuthorizationController

import com.google.common.cache.RemovalNotification; //導入依賴的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);
				}
			});
}
 
開發者ID:tojaoomy,項目名稱:private-WeChat,代碼行數:26,代碼來源:AuthorizationController.java

示例5: onRemoval

import com.google.common.cache.RemovalNotification; //導入依賴的package包/類
@Override
public void onRemoval(RemovalNotification<CacheKey, CompiledScript> notification) {
    if (logger.isDebugEnabled()) {
        logger.debug("notifying script services of script removal due to: [{}]", notification.getCause());
    }
    scriptMetrics.onCacheEviction();
    for (ScriptEngineService service : scriptEngines) {
        try {
            service.scriptRemoved(notification.getValue());
        } catch (Exception e) {
            logger.warn("exception calling script removal listener for script service", e);
            // We don't rethrow because Guava would just catch the
            // exception and log it, which we have already done
        }
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:17,代碼來源:ScriptService.java

示例6: onRemoval

import com.google.common.cache.RemovalNotification; //導入依賴的package包/類
@Override
public void onRemoval(RemovalNotification<Object, Cache<Query, Value>> notification) {
    Object key = notification.getKey();
    if (key == null) {
        return;
    }

    Cache<Query, Value> valueCache = notification.getValue();
    if (valueCache == null) {
        return;
    }

    for (Value value : valueCache.asMap().values()) {
        listener.onRemoval(value.shardId, value.bitset);
        // if null then this means the shard has already been removed and the stats are 0 anyway for the shard this key belongs to
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:18,代碼來源:BitsetFilterCache.java

示例7: KeyProviderCache

import com.google.common.cache.RemovalNotification; //導入依賴的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();
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:20,代碼來源:KeyProviderCache.java

示例8: init

import com.google.common.cache.RemovalNotification; //導入依賴的package包/類
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.serviceDirectory = context.directory();
    this.deviceId = deviceId;

    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    flowObjectiveStore = serviceDirectory.get(FlowObjectiveStore.class);

    pendingNext = CacheBuilder.newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<Integer, NextObjective> notification) -> {
                if (notification.getCause() == RemovalCause.EXPIRED) {
                    notification.getValue().context()
                            .ifPresent(c -> c.onError(notification.getValue(),
                                    ObjectiveError.FLOWINSTALLATIONFAILED));
                }
            }).build();
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:19,代碼來源:DefaultSingleTablePipeline.java

示例9: activate

import com.google.common.cache.RemovalNotification; //導入依賴的package包/類
@Activate
public void activate() {
    providerService = providerRegistry.register(this);

    pendingOperations = CacheBuilder.newBuilder()
            .expireAfterWrite(TIMEOUT, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<Long, MeterOperation> notification) -> {
                if (notification.getCause() == RemovalCause.EXPIRED) {
                    providerService.meterOperationFailed(notification.getValue(),
                                                         MeterFailReason.TIMEOUT);
                }
            }).build();

    controller.addEventListener(listener);
    controller.addListener(listener);

    controller.getSwitches().forEach((sw -> createStatsCollection(sw)));
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:19,代碼來源:OpenFlowMeterProvider.java

示例10: onRemoval

import com.google.common.cache.RemovalNotification; //導入依賴的package包/類
public void onRemoval(RemovalNotification<Integer, StatementInfo> notification) {
  Integer stmtId = notification.getKey();
  StatementInfo doomed = notification.getValue();
  if (doomed == null) {
    // log/throw?
    return;
  }
  LOG.debug("Expiring statement {} because {}", stmtId, notification.getCause());
  try {
    if (doomed.getResultSet() != null) {
      doomed.getResultSet().close();
    }
    if (doomed.statement != null) {
      doomed.statement.close();
    }
  } catch (Throwable t) {
    LOG.info("Exception thrown while expiring statement {}", stmtId, t);
  }
}
 
開發者ID:apache,項目名稱:calcite-avatica,代碼行數:20,代碼來源:JdbcMeta.java

示例11: initExcludedNodes

import com.google.common.cache.RemovalNotification; //導入依賴的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;
        }
      });
}
 
開發者ID:aliyun-beta,項目名稱:aliyun-oss-hadoop-fs,代碼行數:20,代碼來源:DataStreamer.java

示例12: createCache

import com.google.common.cache.RemovalNotification; //導入依賴的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();
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-management-java,代碼行數:34,代碼來源:CheckAggregationOptions.java

示例13: createCache

import com.google.common.cache.RemovalNotification; //導入依賴的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();
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-management-java,代碼行數:34,代碼來源:ReportAggregationOptions.java

示例14: onRemoval

import com.google.common.cache.RemovalNotification; //導入依賴的package包/類
@Override
public void onRemoval(RemovalNotification<K, V> notification)
{
    switch (notification.getCause())
    {
        case EXPIRED:
            notifyListeners(new GuavaCacheEntryEvent<>(this, EventType.EXPIRED, notification));
            break;

        case EXPLICIT:
            notifyListeners(new GuavaCacheEntryEvent<>(this, EventType.REMOVED, notification));
            break;

        case REPLACED:
            notifyListeners(new GuavaCacheEntryEvent<>(this, EventType.UPDATED, notification));
            break;
    }
}
 
開發者ID:ocafebabe,項目名稱:guava-jcache,代碼行數:19,代碼來源:GuavaCache.java

示例15: CircuitBreakerRegistryImpl

import com.google.common.cache.RemovalNotification; //導入依賴的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);
            }
          });
}
 
開發者ID:edgar615,項目名稱:direwolves,代碼行數:26,代碼來源:CircuitBreakerRegistryImpl.java


注:本文中的com.google.common.cache.RemovalNotification類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。