下面列出了怎么用com.codahale.metrics.Timer.Context的API类实例代码及写法,或者点击链接到github查看源代码。
public LinkRelevance nextURL(boolean asyncLoad) throws FrontierPersistentException, DataNotFoundException {
Context timerContext = selectTimer.time();
try {
LinkRelevance link = scheduler.nextLink(asyncLoad);
if (link == null) {
if (scheduler.hasPendingLinks()) {
throw new DataNotFoundException(false, "No links available for selection right now.");
} else {
throw new DataNotFoundException(true, "Frontier run out of links.");
}
}
frontier.delete(link);
schedulerLog.printf("%d\t%.5f\t%s\n", System.currentTimeMillis(),
link.getRelevance(), link.getURL().toString());
return link;
} finally {
timerContext.stop();
}
}
@Nullable
@Override
public T findById(I id) {
if(id == null) {
return null;
}
BoundStatement boundStatement = new BoundStatement(findById);
Row row;
try(Context ctxt = findByIdTimer.time()) {
row = session.execute(boundStatement.bind(id)).one();
}
if(row == null) {
return null;
}
return buildEntity(row);
}
/**
* 根据数据源名称获取全部数据库连接.
*
* @param dataSourceName 数据源名称
* @return 数据库连接集合
* @throws SQLException SQL异常
*/
public Collection<Connection> getConnectionForDDL(final String dataSourceName) throws SQLException {
final Context metricsContext = MetricsContext.start(Joiner.on("-").join("ShardingConnection-getConnectionForDDL", dataSourceName));
// 从分片规则的数据库分片规则中获取数据源
DataSource dataSource = shardingContext.getShardingRule().getDataSourceRule().getDataSource(dataSourceName);
Preconditions.checkState(null != dataSource, "Missing the rule of %s in DataSourceRule", dataSourceName);
Collection<DataSource> dataSources = new LinkedList<>();
if (dataSource instanceof MasterSlaveDataSource) {
dataSources.add(((MasterSlaveDataSource) dataSource).getMasterDataSource());
dataSources.addAll(((MasterSlaveDataSource) dataSource).getSlaveDataSources());
} else {
dataSources.add(dataSource);
}
Collection<Connection> result = new LinkedList<>();
for (DataSource each : dataSources) {
// 根据数据源获取数据库连接
Connection connection = each.getConnection();
replayMethodsInvocation(connection);//重新调用调用过的方法动作
result.add(connection);
}
MetricsContext.stop(metricsContext);
return result;
}
/**
* 执行SQL查询.
*
* @return 结果集列表
*/
public List<ResultSet> executeQuery() {
Context context = MetricsContext.start("ShardingPreparedStatement-executeQuery");
List<ResultSet> result;
try {
result = executorEngine.executePreparedStatement(sqlType, preparedStatementUnits, parameters, new ExecuteCallback<ResultSet>() {
@Override
public ResultSet execute(final BaseStatementUnit baseStatementUnit) throws Exception {
return ((PreparedStatement) baseStatementUnit.getStatement()).executeQuery();
}
});
} finally {
MetricsContext.stop(context);
}
return result;
}
/**
* 执行SQL请求.
*
* @return true表示执行DQL, false表示执行的DML
*/
public boolean execute() {
Context context = MetricsContext.start("ShardingPreparedStatement-execute");
try {
List<Boolean> result = executorEngine.executePreparedStatement(sqlType, preparedStatementUnits, parameters, new ExecuteCallback<Boolean>() {
@Override
public Boolean execute(final BaseStatementUnit baseStatementUnit) throws Exception {
return ((PreparedStatement) baseStatementUnit.getStatement()).execute();
}
});
if (null == result || result.isEmpty() || null == result.get(0)) {
return false;
}
return result.get(0);
} finally {
MetricsContext.stop(context);
}
}
/**
* 执行SQL查询.
*
* @return 结果集列表
*/
public List<ResultSet> executeQuery() {
Context context = MetricsContext.start("ShardingStatement-executeQuery");
List<ResultSet> result;
try {
result = executorEngine.executeStatement(sqlType, statementUnits, new ExecuteCallback<ResultSet>() {
@Override
public ResultSet execute(final BaseStatementUnit baseStatementUnit) throws Exception {
return baseStatementUnit.getStatement().executeQuery(baseStatementUnit.getSqlExecutionUnit().getSql());
}
});
} finally {
MetricsContext.stop(context);
}
return result;
}
private Observable<Boolean> directPoster(Observable<List<Sample>> samples, MetricRegistry metrics) {
final SampleRepository repository = repository();
final Timer timer = metrics.timer("writes");
final Meter completions = metrics.meter("samples-completed");
Func1<List<Sample>, Boolean> insert = new Func1<List<Sample>, Boolean>() {
@Override
public Boolean call(List<Sample> s) {
int sz = s.size();
try (Context timerCtx = timer.time()) {
repository.insert(s);
return true;
} finally {
completions.mark(sz);
}
}
};
return (m_threadCount == 1 ? samples.map(insert) : parMap(samples, metrics, insert)).all(Functions.<Boolean>identity());
}
@Override
public Login findLogin(String username) {
Row row;
try(Context ctxt = findLoginTimer.time()) {
row = findLoginRowByUsername(username);
}
if(row == null) {
return null;
}
Login login = new Login();
login.setPassword(row.getString(LoginColumns.PASSWORD));
login.setPasswordSalt(row.getString(LoginColumns.PASSWORD_SALT));
login.setUserId(row.getUUID(LoginColumns.USERID));
login.setUsername(username);
login.setLastPasswordChange(row.getTimestamp(LoginColumns.LAST_PASS_CHANGE));
return login;
}
@Override
public Person deletePinAtPlace(Person person, UUID placeId)
{
Preconditions.checkArgument(person != null, "person cannot be null");
Preconditions.checkArgument(placeId != null, "placeId cannot be null");
try (Context timerContext = updatePinAtPlaceTimer.time())
{
Date modified = new Date();
boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);
Statement deleteStatement = isCurrentPlace ?
new BoundStatement(updatePinAtPlaceAndPin2).bind(modified, placeId.toString(), null, null, person.getId()) :
new BoundStatement(updatePinAtPlace).bind(modified, placeId.toString(), null, person.getId());
session.execute(deleteStatement);
Person copy = person.copy();
copy.setModified(modified);
copy.clearPin(placeId);
return copy;
}
}
@Override
public void delete(T entity) {
if(entity == null || entity.getId() == null) {
return;
}
Statement statement = new BoundStatement(delete).bind(entity.getId());
List<Statement> indexDeletes = prepareIndexDeletes(entity);
if(!indexDeletes.isEmpty()) {
BatchStatement batch = new BatchStatement();
batch.add(statement);
addToBatch(batch, indexDeletes);
statement = batch;
}
try(Context ctxt = deleteTimer.time()) {
session.execute(statement);
}
}
@Override
public Map<String, Object> findById(UUID personId, UUID placeId)
{
BoundStatement boundStatement = new BoundStatement(findByIdStatement)
.setUUID(Cols.PERSON_ID, personId)
.setUUID(Cols.PLACE_ID, placeId);
Row row;
try (Context context = findByIdTimer.time())
{
row = session.execute(boundStatement).one();
}
if (row == null)
{
return null;
}
Map<String, String> prefsEncoded = row.getMap(Cols.PREFS, String.class, String.class);
return decodeAttributesFromJson(prefsEncoded, Preferences.TYPE);
}
/**
* A timer measures both the rate that a particular piece of code is called and the distribution
* of its duration. For example we want to measure the rate and handling duration of incoming
* requests.
*/
private static void reportTimer() {
// Create or fetch (if it is already created) the metric.
final Timer timer = registry.timer(
APP_PREFIX.tagged("what", "incoming-request-time").tagged("endpoint", "/v1/get_stuff"));
// Do this before starting to do the thing. This creates a measurement context object
// that you can pass around.
final Context context = timer.time();
// Do stuff that takes time (e.g., process the request)
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
e.printStackTrace();
}
// Tell the context that it's done. This will register the duration and counts one
// occurrence.
context.stop();
// That's it! The rest will be automatically done inside semantic metrics library. The
// reported measurements will be kept in the registry.
// Every time the reporter wants to report, different stats and aggregations (all the
// stats that you would get from a meter and a histogram are included) will be calculated
// and
// datapoints will be created and reported.
}
@Override
public Object fetchAttribute(AttributeLocation<JMXNodeLocation> location) throws ProtocolException {
try {
String[] attribute = location.getAttribute().split("#", 2);
J4pReadRequest request = new J4pReadRequest(location.getLocation().getObjectName(), attribute[0]);
if (attribute.length > 1) {
request.setPath(attribute[1]); // this is the sub-reference
}
J4pReadResponse response;
try (Context timerContext = getDiagnostics().getRequestTimer().time()) {
response = client.execute(request);
}
Collection<ObjectName> responseObjectNames = response.getObjectNames();
switch (responseObjectNames.size()) {
case 0:
return null;
case 1:
return response.getValue();
default:
List<Object> results = new ArrayList<>(responseObjectNames.size());
for (ObjectName responseObjectName : responseObjectNames) {
Object value = response.getValue(responseObjectName, location.getAttribute());
results.add(value);
}
return Collections.unmodifiableList(results);
}
} catch (Exception e) {
getDiagnostics().getErrorRate().mark(1);
throw new ProtocolException(e);
}
}
private int executeUpdate(final Updater updater) {
Context context = MetricsContext.start("ShardingStatement-executeUpdate");
try {
List<Integer> results = executorEngine.executeStatement(sqlType, statementUnits, new ExecuteCallback<Integer>() {
@Override
public Integer execute(final BaseStatementUnit baseStatementUnit) throws Exception {
return updater.executeUpdate(baseStatementUnit.getStatement(), baseStatementUnit.getSqlExecutionUnit().getSql());
}
});
return accumulate(results);
} finally {
MetricsContext.stop(context);
}
}
@Override
public ModelEntity findHubModel(String id) {
try(Context ctxt = findHubModelTimer.time()) {
BoundStatement boundStatement = new BoundStatement(findById);
boundStatement.bind(id);
Row r = session.execute(boundStatement).one();
return toModel(r);
}
}
@Override
public List<StreetAddress> getSuggestions(StreetAddress address)
{
try (Context timerContext = requestTimerMetric.tag("op", "getSuggestions").time())
{
String jsonResponse = sendRequest(address);
return gson.fromJson(jsonResponse, streetAddressesType);
}
}
@Override
public Hub findHubForPlace(UUID placeId) {
if(placeId == null) {
return null;
}
BoundStatement boundStatement = new BoundStatement(findIdForPlace);
try(Context ctxt = findHubForPlaceTimer.time()) {
Row row = session.execute(boundStatement.bind(placeId)).one();
if(row == null) {
return null;
}
return findById(row.getString("hubid"));
}
}
public TemplatedResponse doHandle(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception {
Context timer = WEBHOOK_TIMER.time();
try{
String recurlyXML = request.content().toString(CharsetUtil.UTF_8);
Document document = XMLHelper.parse(recurlyXML);
String transactionType = document.getDocumentElement().getTagName();
WebhookHandler<? extends Object>handler=handlers.get(transactionType);
if(transactionType.equals(TRANS_TYPE_CLOSED_INVOICE_NOTIFICATION)){
ClosedInvoiceNotification notification = XMLHelper.unmarshall(document,ClosedInvoiceNotification.class);
((WebhookHandler)handler).handleWebhook(notification);
}
else{
IGNORED_COUNTER.inc();
LOGGER.info(MSG_IGNORE_NOTIFICATION);
}
return createTemplateResponse(HttpResponseStatus.NO_CONTENT);
}
catch(Exception e){
ERRORED_COUNTER.inc();
LOGGER.error("Unknown error processing recurly webhook",e);
return createTemplateResponse(HttpResponseStatus.BAD_REQUEST);
}
finally{
timer.stop();
}
}
@Override
public Stream<RuleEnvironment> streamAll() {
Context timer = RuleEnvironmentDaoMetrics.streamAllTimer.time();
Iterator<Row> rows = session.execute(streamAll.bind()).iterator();
Iterator<RuleEnvironment> result = new RuleEnvironmentIterator(timer, rows);
Spliterator<RuleEnvironment> stream = Spliterators.spliteratorUnknownSize(result, Spliterator.IMMUTABLE | Spliterator.NONNULL);
return StreamSupport.stream(stream, false);
}
@Override
public RuleEnvironment findByPlace(UUID placeId) {
Preconditions.checkNotNull(placeId, "placeId may not be null");
RuleEnvironmentAggregator aggregator = new RuleEnvironmentAggregator(placeId);
// TODO check that place exists?
try(Context c = RuleEnvironmentDaoMetrics.findByPlaceTimer.time()) {
BoundStatement bs = listByPlace.bind(placeId);
for(Row row: session.execute( bs )) {
aggregator.addRow(row);
}
}
return aggregator.build();
}
@Override
public void deleteByPlace(UUID placeId) {
if(placeId == null) {
return;
}
try(Context c = RuleEnvironmentDaoMetrics.deleteByPlaceTimer.time()) {
BoundStatement bs = deleteByPlace.bind(placeId);
session.execute( bs );
// TODO throw if was applied = false
}
}
public List<T> listByPlace(UUID placeId) {
Preconditions.checkNotNull(placeId, "placeId may not be null");
List<T> beans = new ArrayList<T>();
try(Context c = metrics.startListByPlaceTimer()) {
ResultSet rs = session.execute( listByPlace.bind(placeId) );
for(Row row: rs) {
T bean = buildEntity(row);
beans.add(bean);
}
return beans;
}
}
@Override
public void timed(@NotNull Runnable r, @NotNull String timerName) {
final Context context = getNamedTimer(timerName).time();
try {
r.run();
}
finally {
context.stop();
}
}
public void save(T bean) {
Preconditions.checkNotNull(bean, "definition may not be null");
Preconditions.checkArgument(bean.getPlaceId() != null, "object must be associated with a place");
boolean insert = !bean.isPersisted();
Context c;
Statement stmt;
if(insert) {
c = metrics.startDaoCreateTimer();
}
else {
c = metrics.startDaoUpdateTimer();
}
try {
Date ts = new Date();
if(insert) {
stmt = prepareInsert(bean, ts);
}
else {
stmt = prepareUpdate(bean, ts);
}
ResultSet rs = session.execute( stmt );
if(!rs.wasApplied()) {
throw new IllegalStateException("Failed to persist object");
}
}
finally {
c.close();
}
}
public boolean delete(UUID placeId, Integer sequenceId) {
if(placeId == null || sequenceId == null) {
return false;
}
try(Context c = metrics.startDaoDeleteTimer()) {
BoundStatement bs = deleteById.bind(placeId, sequenceId);
return session.execute( bs ).wasApplied();
}
}
@Override
public void accept(String code) {
Preconditions.checkNotNull(code, "code is required");
try(Context timer = acceptTimer.time()) {
BoundStatement stmt = new BoundStatement(acceptExistingPerson);
stmt.setString(Column.code.name(), StringUtils.lowerCase(code));
stmt.setTimestamp(Column.accepted.name(), new Date());
session.execute(stmt);
}
}
@Override
public ModelEntity findHubModelForPlace(UUID placeId) {
if(placeId == null) {
return null;
}
try(Context ctxt = findHubModelForPlaceTimer.time()) {
BoundStatement boundStatement = new BoundStatement(findIdForPlace);
Row row = session.execute(boundStatement.bind(placeId)).one();
if(row == null) {
return null;
}
return findHubModel(row.getString("hubid"));
}
}
@Test
public void testOpenCloseConnections() throws SQLException {
for (int i = 0; i < MAX_ITERATIONS; i++) {
Context context = timer.time();
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
stmt.executeQuery("select * from city");
conn.close();
context.stop();
}
logReporter.report();
}
@Override
public MobileDevice findOne(UUID personId, int instance) {
Preconditions.checkNotNull(personId, "The person ID cannot be null");
try(Context ctxt = findOneTimer.time()) {
Row row = session.execute(new BoundStatement(findOneQuery).bind(personId, instance)).one();
return row == null ? null : createMobileDevice(row);
}
}
private PairingDevice update(PairingDevice entity) {
Preconditions.checkState(entity.getId() != null, "Attempting to update a pairing device model with a create date but no secondary id");
try(Context ctx = Metrics.updateTimer.time()) {
Date modified = new Date();
BoundStatement bs = updateIf.bind( encode( entity.getAttributes() ), modified, entity.getPlaceId(), entity.getProtocolAddress().getRepresentation() );
if(!session().execute( bs ).wasApplied()) {
throw new NotFoundException(entity.getAddress());
}
PairingDevice copy = entity.copy();
copy.setModified(modified);
return copy;
}
}