本文整理汇总了Java中com.codahale.metrics.Timer.Context类的典型用法代码示例。如果您正苦于以下问题:Java Context类的具体用法?Java Context怎么用?Java Context使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Context类属于com.codahale.metrics.Timer包,在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: allLinks
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@RequestMapping("/all-links")
public String allLinks(Model model) {
Timer timer = metricRegistry.timer("all-links");
Context context = timer.time();
try {
List<Link> asdex = linkRepo.findByNameContainingOrderByNameAsc("ASDE-X");
model.addAttribute("asdex", asdex);
List<Link> assc = linkRepo.findByNameContainingOrderByNameAsc("ASSC");
model.addAttribute("assc", assc);
List<Link> tdls = linkRepo.findByNameContainingOrderByNameAsc("TDLS");
model.addAttribute("tdls", tdls);
List<Link> efsts = linkRepo.findByNameContainingOrderByNameAsc("EFSTS");
model.addAttribute("efsts", efsts);
List<Link> stars = linkRepo.findByNameContainingOrderByNameAsc("STARS");
model.addAttribute("stars", stars);
List<Link> rvr = linkRepo.findByNameContainingOrderByNameAsc("RVR");
model.addAttribute("rvr", rvr);
return "all-links";
} finally {
context.stop();
}
}
示例2: serialOf
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Override
public OptionalLong serialOf(UUID l) {
try (Context time = seqLookupLatency.time();) {
List<Long> res = jdbcTemplate.query(PGConstants.SELECT_SER_BY_ID, new Object[] {
"{\"id\":\"" + l + "\"}" }, this::extractSerFromResultSet);
if (res.size() > 1) {
throw new IllegalStateException("Event ID appeared twice!?");
} else if (res.isEmpty()) {
return OptionalLong.empty();
}
Long ser = res.get(0);
if (ser != null && ser.longValue() > 0) {
return OptionalLong.of(ser.longValue());
} else {
return OptionalLong.empty();
}
}
}
示例3: run
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Override
public void run() {
try (final Context context = metrics.getDownloadTimer().time()) {
download();
} catch (Throwable t) {
metrics.getServerErrorsMeter().mark();
LOG.error("While handling {}", artifactDownloadRequest.getTargetDirectory(), t);
exceptionNotifier.notify(t, ImmutableMap.of("s3Bucket", artifactDownloadRequest.getS3Artifact().getS3Bucket(), "s3Key", artifactDownloadRequest.getS3Artifact().getS3ObjectKey(), "targetDirectory", artifactDownloadRequest.getTargetDirectory()));
try {
getResponse().sendError(500);
} catch (Throwable t2) {
LOG.error("While sending error for {}", artifactDownloadRequest.getTargetDirectory(), t2);
}
} finally {
continuation.complete();
}
}
示例4: add
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
/**
* Will block until there is space for the query to be submitted
*/
public Observable<QueryResponse> add(Query<?> query, Keyspace keyspace, boolean keepErrors) {
QueryRequest queryRequest = new QueryRequest(query);
queryRequest.acquirePermit();
Context context = addTimer.time();
Observable<QueryResponse> observable = new QueriesObservableCollapser(queryRequest, keyspace)
.observe()
.doOnError((error) -> failureMeter.mark())
.doOnEach(a -> {
if (a.getThrowable() != null) {
LOG.error("Error while executing statement", a.getThrowable());
} else if (a.isOnNext()) {
LOG.trace("Executed {}", a.getValue());
}
})
.subscribeOn(scheduler)
.doOnTerminate(context::close);
return keepErrors ? observable : ignoreErrors(observable);
}
示例5: run
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Override
protected List<QueryResponse> run() throws GraknClientException {
List<Query<?>> queryList = queries.stream().map(QueryRequest::getQuery)
.collect(Collectors.toList());
try {
return retryer.call(() -> {
try (Context c = graqlExecuteTimer.time()) {
return graknClient.graqlExecute(queryList, keyspace);
}
});
} catch (RetryException | ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof GraknClientException) {
throw (GraknClientException) cause;
} else {
throw new RuntimeException("Unexpected exception while retrying, " + queryList.size() + " queries failed.", e);
}
} finally {
queries.forEach(QueryRequest::releasePermit);
}
}
示例6: start
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
/**
* Apply {@link ai.grakn.concept.Attribute} post processing jobs the concept ids in the provided configuration
*
* @return True if successful.
*/
@Override
public boolean start() {
try (Context context = metricRegistry()
.timer(name(PostProcessingTask.class, "execution")).time()) {
CommitLog commitLog = getPostProcessingCommitLog(configuration());
commitLog.attributes().forEach((conceptIndex, conceptIds) -> {
Context contextSingle = metricRegistry()
.timer(name(PostProcessingTask.class, "execution-single")).time();
try {
Keyspace keyspace = commitLog.keyspace();
int maxRetry = engineConfiguration().getProperty(GraknConfigKey.LOADER_REPEAT_COMMITS);
GraknTxMutators.runMutationWithRetry(factory(), keyspace, maxRetry,
(graph) -> postProcessor().mergeDuplicateConcepts(graph, conceptIndex, conceptIds));
} finally {
contextSingle.stop();
}
});
LOG.debug(JOB_FINISHED, Schema.BaseType.ATTRIBUTE.name(), commitLog.attributes());
return true;
}
}
示例7: mget
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
public JsonArray mget(String...keys) {
try(Context context = mgetTimer.time()) {
JsonArray results=array();
try(Jedis resource = jedisPool.getResource()) {
byte[][] byteKeys = Arrays.stream(keys).map(key -> key(key)).toArray(size -> new byte[size][]);
List<byte[]> redisResults = resource.mget(byteKeys);
if(redisResults!=null) {
for(byte[] blob:redisResults) {
if(blob != null) {
// some results will be null
results.add(parser.parseObject(new String(CompressionUtils.decompress(blob), utf8)));
}
}
}
} catch (JedisException e) {
// make sure we can find back jedis related stuff in kibana
throw new IllegalStateException("problem connecting to jedis", e);
}
notFoundMeter.mark();
return results;
}
}
示例8: create
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Override
public JsonObject create(JsonObject o, String parentId, boolean replace) {
try(Context time = createTimer.time()) {
JsonObject object;
if(defaultTransformation != null) {
object=defaultTransformation.apply(o);
} else {
object=o;
}
JsonObject esResponse = client.createObject(index.writeAlias(), type,object.getString("id"), parentId, object, replace);
JsonObject response = object.deepClone();
// make sure the id aligns with the actual id in elasticsearch
String id = esResponse.getString("_id");
response.put("id", id);
markModifiedInRedis(id, parentId);
return response;
}
}
示例9: create
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Override
public JsonObject create(JsonObject o, boolean replace) {
try(Context time = createTimer.time()) {
JsonObject object;
if(defaultTransformation != null) {
object = defaultTransformation.apply(o);
} else {
object=o;
}
JsonObject esResponse = client.createObject(index.writeAlias(), type,object.getString("id"), null, object, replace);
if(esResponse.get("_shards","successful").asInt() != 1) {
throw new EsOperationFailedException("Elasticsearch create did not succeeed " + esResponse);
}
// Elasticsearch does not return us the full object
JsonObject response = object.deepClone();
// make sure the id aligns with the actual id in elasticsearch
response.put("id", esResponse.getString("_id"));
return response;
}
}
示例10: onEvent
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Override
public void onEvent(final TSDBMetricMeta meta, final long sequence, final boolean endOfBatch) throws Exception {
final Context ctx = dispatchHandlerTimer.time();
try {
if(outQueueTextFormat) {
outQueue.acquireAppender().writeDocument(w -> w.write(MessageType.METRICMETA.shortName).marshallable(meta));
} else {
outQueue.acquireAppender().writeBytes(meta);
}
cacheDb.add(meta.getTsuid());
meta.recordTimer(endToEndTimer);
} finally {
meta.reset();
ctx.stop();
}
}
示例11: testRedisRateLimit
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@Test
public void testRedisRateLimit() throws InterruptedException {
reporter.start(3, TimeUnit.SECONDS);
ApplicationContext ac = new ClassPathXmlApplicationContext("root-context.xml");
JedisPool pool = (JedisPool) ac.getBean("jedisPool");
RedisRateLimiter limiter = new RedisRateLimiter(pool, TimeUnit.MINUTES, 300);
while (true) {
boolean flag = false;
Context context = timer.time();
if(limiter.acquire("testMKey1")) {
flag = true;
}
context.stop();
if (flag) {
requests.mark();
}
Thread.sleep(1);
}
}
示例12: runCompaction
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
private void runCompaction(File commitLogFile) {
if (runCompactions) {
compactionExecutor.submit(new Runnable() {
@Override
public void run() {
try {
Context time = compactionTime.time();
Compactor.run(storage, directory, commitLogFile, configuration.getBufferSize(),
configuration.getMaxDataFileSize(), configuration.getMaxFileGenerations());
openDataFiles();
deleteCommitLogFiles(commitLogFile);
compactionCounter.inc();
time.stop();
} catch (Exception e) {
logger.error("Could not run compaction.", e);
}
}
});
}
}
示例13: expected
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
/**
* Return an expected session for the user, falling back to database retrieval
* should the session not yet exist in cache.
*
* @param userName
* the user name
* @return the user session
* @throws GameBootRuntimeException
* the game boot runtime exception
*/
public UserSession expected(String userName) throws GameBootRuntimeException {
Optional<Context> ctx = helper.startTimer(CACHED_SESSION_TIMER);
try {
String noSession = "No session for " + userName;
check(NO_USERNAME, isEmpty(userName), "No username specified");
check(NO_USER_SESSION, !activeSessions.hasSession(userName), noSession);
List<UserSession> sessions = assist.activeSessions();
Optional<UserSession> o = find(sessions, us -> us.getUser().getUserName().equals(userName));
// may not yet be in the cached list
return o.isPresent() ? o.get() : sessionCheck(repository.findOpenSession(userName));
} finally {
helper.stopTimer(ctx);
}
}
示例14: convert
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
/**
* Will encode the message if decoded, decode the message if encoded.
*
* @param key
* the key
* @param message
* the message byte array
* @return the converted byte array
* @throws Exception
* the exception
*/
public byte[] convert(byte[] key, byte[] message) throws Exception {
Optional<Context> ctx = helper.startTimer(OTP_CONVERSION);
try {
check(key, message);
byte[] converted = new byte[message.length];
for (int i = 0; i < message.length; i++) {
converted[i] = (byte) (message[i] ^ key[i]);
}
return converted;
} finally {
helper.stopTimer(ctx);
}
}
示例15: fetchNodes
import com.codahale.metrics.Timer.Context; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public Map<JMXNodeLocation, ObjectName> fetchNodes(JMXNodeLocation query) throws ProtocolException {
try {
Set<ObjectName> searchResponse;
try (Context timerContext = getDiagnostics().getRequestTimer().time()) {
searchResponse = this.mbs.queryNames(query.getObjectName(), null);
}
Map<JMXNodeLocation, ObjectName> result = new HashMap<>();
for (ObjectName objectName : searchResponse) {
JMXNodeLocation location = new JMXNodeLocation(objectName);
result.put(location, objectName);
}
return Collections.unmodifiableMap(result);
} catch (Exception e) {
getDiagnostics().getErrorRate().mark(1);
throw new ProtocolException(e);
}
}