• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中io.micrometer.core.instrument.Timer的典型用法代码示例。如果您正苦于以下问题:Java Timer类的具体用法?Java Timer怎么用?Java Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Timer类属于io.micrometer.core.instrument包,在下文中一共展示了Timer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: recordCallableException

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("callable task that throws exception is still recorded")
default void recordCallableException(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");

    assertThrows(Exception.class, () -> {
        t.recordCallable(() -> {
            clock(registry).add(10, TimeUnit.NANOSECONDS);
            throw new Exception("uh oh");
        });
    });

    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:18,代码来源:TimerTest.java


示例2: record

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
private void record(TimingSampleContext timingContext, HttpServletResponse response, HttpServletRequest request,
                    Object handlerObject, Throwable e) {
    for (Timed timedAnnotation : timingContext.timedAnnotations) {
        timingContext.timerSample.stop(Timer.builder(timedAnnotation, metricName)
            .tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
            .register(registry));
    }

    if(timingContext.timedAnnotations.isEmpty() && autoTimeRequests) {
        timingContext.timerSample.stop(Timer.builder(metricName)
            .tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
            .register(registry));
    }

    for (LongTaskTimer.Sample sample : timingContext.longTaskTimerSamples) {
        sample.stop();
    }
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:19,代码来源:MetricsFilter.java


示例3: time

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
private void time(CallState state) {
    String uri = state.response == null ? "UNKNOWN" :
        (state.response.code() == 404 || state.response.code() == 301 ? "NOT_FOUND" : urlMapper.apply(state.request));

    Iterable<Tag> tags = Tags.concat(extraTags, Tags.zip(
        "method", state.request != null ? state.request.method() : "UNKNOWN",
        "uri", uri,
        "status", getStatusMessage(state.response, state.exception),
        "host", state.request != null ? state.request.url().host() : "UNKNOWN"
    ));

    Timer.builder(this.requestsMetricName)
        .tags(tags)
        .description("Timer of OkHttp operation")
        .register(registry)
        .record(registry.config().clock().monotonicTime() - state.startTime, TimeUnit.NANOSECONDS);
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:18,代码来源:OkHttpMetricsEventListener.java


示例4: registerNewMeter

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Override
Timer registerNewMeter(MeterRegistry registry) {
    final long[] slaNanos = histogramConfig.getSlaBoundaries();

    Duration[] sla = null;
    if(slaNanos != null) {
        sla = new Duration[slaNanos.length];
        for (int i = 0; i < slaNanos.length; i++) {
            sla[i] = Duration.ofNanos(slaNanos[i]);
        }
    }

    return Timer.builder(getId().getName())
                .tags(getId().getTags())
                .description(getId().getDescription())
                .maximumExpectedValue(Duration.ofNanos(histogramConfig.getMaximumExpectedValue()))
                .minimumExpectedValue(Duration.ofNanos(histogramConfig.getMinimumExpectedValue()))
                .publishPercentiles(histogramConfig.getPercentiles())
                .publishPercentileHistogram(histogramConfig.isPercentileHistogram())
                .histogramBufferLength(histogramConfig.getHistogramBufferLength())
                .histogramExpiry(histogramConfig.getHistogramExpiry())
                .sla(sla)
                .pauseDetector(pauseDetector)
                .register(registry);
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:26,代码来源:CompositeTimer.java


示例5: shortTimers

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
private Set<Timer> shortTimers(Set<Timed> timed, RequestEvent event) {
    /*
     * Given we didn't find any matching resource method, 404s will be only
     * recorded when auto-time-requests is enabled. On par with WebMVC
     * instrumentation.
     */
    if ((timed == null || timed.isEmpty()) && autoTimeRequests) {
        return Collections.singleton(registry.timer(metricName, tagsProvider.httpRequestTags(event)));
    }

    if(timed == null) {
        return Collections.emptySet();
    }

    return timed.stream()
        .map(t -> Timer.builder(t, metricName).tags(tagsProvider.httpRequestTags(event)).register(registry))
        .collect(Collectors.toSet());
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:19,代码来源:MetricsRequestEventListener.java


示例6: stats

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@GetMapping("/api/stats")
public Map<String, Number> stats() {
    Timer t = registry.find("http.server.requests").tags("uri", "/api/people").timer();

    Map<String, Number> result = null;

    if(t != null){
        result = new HashMap<>();

        result.put("count", t.count());
        result.put("max", t.max(TimeUnit.MILLISECONDS));
        result.put("mean", t.mean(TimeUnit.MILLISECONDS));
        result.put("50.percentile", t.percentile(0.5, TimeUnit.MILLISECONDS));
        result.put("95.percentile", t.percentile(0.95, TimeUnit.MILLISECONDS));
    }
    return result;


}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:20,代码来源:PersonController.java


示例7: publish

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Override
protected void publish() {
    List<Metric> metrics = getMeters().stream()
        .flatMap(meter -> {
            if (meter instanceof DistributionSummary) {
                return getMetrics((DistributionSummary) meter);
            } else if (meter instanceof FunctionTimer) {
                return getMetrics((FunctionTimer) meter);
            } else if (meter instanceof Timer) {
                return getMetrics((Timer) meter);
            } else {
                return getMetrics(meter);
            }
        })
        .collect(Collectors.toList());

    this.metricPublisher.publish(metrics);
}
 
开发者ID:cloudfoundry,项目名称:java-buildpack-metric-writer,代码行数:19,代码来源:MicrometerMetricWriter.java


示例8: DataSourceMetricsHolder

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
DataSourceMetricsHolder(String dataSourceName, DataSourcePoolMetadata poolMetadata, MeterRegistry registry) {
    connectionObtainTimer = Timer.builder("data.source.connections.wait")
            .tags("pool", dataSourceName)
            .register(registry);

    connectionUsageTimer = Timer.builder("data.source.connections.usage")
            .tags("pool", dataSourceName)
            .register(registry);

    connectionCreatedCounter = Counter.builder("data.source.connections.created")
            .tags("pool", dataSourceName)
            .register(registry);

    connectionFailedCounter = Counter.builder("data.source.connections.failed")
            .tags("pool", dataSourceName)
            .register(registry);

    Gauge.builder("data.source.connections.active", this, metrics -> activeConnections.doubleValue())
            .tags("pool", dataSourceName)
            .register(registry);

    Gauge.builder("data.source.connections.pending", this, metrics -> pendingConnections.doubleValue())
            .tags("pool", dataSourceName)
            .register(registry);

    if (poolMetadata != null) {
        Gauge.builder("data.source.connections.max", this, metrics -> poolMetadata.getMax())
                .tags("pool", dataSourceName)
                .register(registry);

        Gauge.builder("data.source.connections.min", this, metrics -> poolMetadata.getMin())
                .tags("pool", dataSourceName)
                .register(registry);
    }
}
 
开发者ID:gavlyukovskiy,项目名称:spring-boot-data-source-decorator,代码行数:36,代码来源:DataSourceMetricsHolder.java


示例9: onEvent

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Override
public void onEvent(RequestEvent event) {
    ContainerRequest containerRequest = event.getContainerRequest();
    Set<Timed> timedAnnotations;

    switch (event.getType()) {
        case ON_EXCEPTION:
            if(!(event.getException() instanceof NotFoundException)) {
                break;
            }
        case REQUEST_MATCHED:
            timedAnnotations = annotations(event);

            timedAnnotationsOnRequest.put(containerRequest, timedAnnotations);
            shortTaskSample.put(containerRequest, Timer.start(registry));

            List<LongTaskTimer.Sample> longTaskSamples = longTaskTimers(timedAnnotations, event).stream().map(LongTaskTimer::start).collect(Collectors.toList());
            if (!longTaskSamples.isEmpty()) {
                this.longTaskSamples.put(containerRequest, longTaskSamples);
            }
            break;
        case FINISHED:
            timedAnnotations = timedAnnotationsOnRequest.remove(containerRequest);
            Timer.Sample shortSample = shortTaskSample.remove(containerRequest);

            if (shortSample != null) {
                for (Timer timer : shortTimers(timedAnnotations, event)) {
                    shortSample.stop(timer);
                }
            }

            Collection<LongTaskTimer.Sample> longSamples = this.longTaskSamples.remove(containerRequest);
            if (longSamples != null) {
                for (LongTaskTimer.Sample longSample : longSamples) {
                    longSample.stop();
                }
            }
            break;
    }
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:41,代码来源:MetricsRequestEventListener.java


示例10: record

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("total time and count are preserved for a single timing")
default void record(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(42, TimeUnit.MILLISECONDS);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:11,代码来源:TimerTest.java


示例11: recordDuration

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("record durations")
default void recordDuration(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(Duration.ofMillis(42));
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
        () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:11,代码来源:TimerTest.java


示例12: recordNegative

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("negative times are discarded by the Timer")
default void recordNegative(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(-42, TimeUnit.MILLISECONDS);

    assertAll(() -> assertEquals(0L, t.count()),
            () -> assertEquals(0, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:10,代码来源:TimerTest.java


示例13: recordZero

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("zero times contribute to the count of overall events but do not add to total time")
default void recordZero(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(0, TimeUnit.MILLISECONDS);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(0L, t.totalTime(TimeUnit.NANOSECONDS)));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:11,代码来源:TimerTest.java


示例14: recordWithRunnable

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("record a runnable task")
default void recordWithRunnable(MeterRegistry registry) throws Exception {
    Timer t = registry.timer("myTimer");

    try {
        t.record(() -> clock(registry).add(10, TimeUnit.NANOSECONDS));
        clock(registry).add(step());
    } finally {
        assertAll(() -> assertEquals(1L, t.count()),
                () -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS) ,1.0e-12));
    }
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:14,代码来源:TimerTest.java


示例15: recordWithSample

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
@DisplayName("record with stateful Sample instance")
default void recordWithSample(MeterRegistry registry) throws Exception {
    Timer timer = registry.timer("myTimer");
    Timer.Sample sample = Timer.start(registry);

    clock(registry).add(10, TimeUnit.NANOSECONDS);
    sample.stop(timer);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, timer.count()),
        () -> assertEquals(10, timer.totalTime(TimeUnit.NANOSECONDS) ,1.0e-12));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:14,代码来源:TimerTest.java


示例16: recordMax

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
default void recordMax(MeterRegistry registry) {
    Timer timer = registry.timer("my.timer");
    timer.record(10, TimeUnit.MILLISECONDS);
    timer.record(1, TimeUnit.SECONDS);

    clock(registry).add(step()); // for Atlas, which is step rather than ring-buffer based
    assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(1);
    assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000);

    clock(registry).add(Duration.ofMillis(step().toMillis() * HistogramConfig.DEFAULT.getHistogramBufferLength()));
    assertThat(timer.max(TimeUnit.SECONDS)).isEqualTo(0);
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:14,代码来源:TimerTest.java


示例17: recordThrowable

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
private Object recordThrowable(Timer timer, ThrowableCallable f) throws Throwable {
    long start = registry.config().clock().monotonicTime();
    try {
        return f.call();
    } finally {
        timer.record(registry.config().clock().monotonicTime() - start, TimeUnit.NANOSECONDS);
    }
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:9,代码来源:ScheduledMethodMetrics.java


示例18: TimingSampleContext

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
TimingSampleContext(HttpServletRequest request, Object handlerObject) {
    timedAnnotations = annotations(handlerObject);
    timerSample = Timer.start(registry);
    longTaskTimerSamples = timedAnnotations.stream()
        .filter(Timed::longTask)
        .map(t -> LongTaskTimer.builder(t)
            .tags(tagsProvider.httpLongRequestTags(request, handlerObject))
            .register(registry)
            .start())
        .collect(Collectors.toList());
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:12,代码来源:MetricsFilter.java


示例19: timerMax

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
@Test
void timerMax() {
    AtlasConfig atlasConfig = k -> null;
    AtlasMeterRegistry registry = new AtlasMeterRegistry(atlasConfig, new MockClock());
    Timer timer = registry.timer("timer");

    timer.record(1, TimeUnit.SECONDS);
    clock(registry).add(atlasConfig.step());
    assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000);
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:11,代码来源:SpectatorTimerTest.java


示例20: main

import io.micrometer.core.instrument.Timer; //导入依赖的package包/类
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    Timer timer = Timer.builder("timer")
        .publishPercentileHistogram()
        .publishPercentiles(0.5, 0.95, 0.99)
        .histogramExpiry(Duration.ofSeconds(10))
        .histogramBufferLength(3)
        .register(registry);

    FunctionTimer.builder("ftimer", timer, Timer::count, t -> t.totalTime(TimeUnit.SECONDS), TimeUnit.SECONDS)
        .register(registry);

    RandomEngine r = new MersenneTwister64(0);
    Normal incomingRequests = new Normal(0, 1, r);
    Normal duration = new Normal(250, 50, r);

    AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
    Flux.interval(Duration.ofSeconds(1))
        .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
        .subscribe();

    // the potential for an "incoming request" every 10 ms
    Flux.interval(Duration.ofMillis(10))
            .doOnEach(d -> {
                if (incomingRequests.nextDouble() + 0.4 > 0) {
                    // pretend the request took some amount of time, such that the time is
                    // distributed normally with a mean of 250ms
                    timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS);
                }
            })
            .blockLast();
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:33,代码来源:TimerSample.java



注:本文中的io.micrometer.core.instrument.Timer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java ScriptScoreFunctionBuilder类代码示例发布时间:2022-05-22
下一篇:
Java JGenericType类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap