当前位置: 首页>>代码示例>>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;未经允许,请勿转载。