Java源码示例:io.micrometer.core.annotation.Timed

示例1
/**
  * POST /users: create a new user
  *
  * @param userDto entity to save
  * @return the ResponseEntity with status 201 (Created) and with body the new user
  * @throws IllegalArgumentException when any given argument is invalid
  */
 @PostMapping
 @Timed
 Mono<ResponseEntity<UserDto>> create(@Valid @RequestBody UserDto userDto) {
   LOGGER.debug("REST request to create a new user : {}", userDto);

   if (Objects.nonNull(userDto.getId())) {
     throw new IllegalArgumentException("A new user cannot already have an ID");
   }

   //@formatter:off
   return userService.create(userDto)
				  .map(createdUser -> ResponseEntity.created(URI.create(String.format("/api/v1/users/%s", createdUser.getId())))
													.body(createdUser));
//@formatter:on
 }
 
示例2
@KafkaListener(topics = {
    "mysqlcdc.cdc.USERS",
    "mysqlcdc.cdc.JOBS",
    "mysqlcdc.cdc.ADDRESSES"})
@Timed
public void handleEvents(List<ConsumerRecord<String, DebeziumEvent>> records,
                            Acknowledgment acknowledgment) {

  LOGGER.debug("Request to process {} records", records.size());

  List<ConsumerRecord<String, DebeziumEvent>> sortedRecords = records.stream()
      .sorted(Comparator.comparing(r -> r.value().getPayload().getDate()))
      .collect(Collectors.toList());

  sortedRecords.forEach(record -> {

    LOGGER.debug("Request to handle {} event in the topic {}", record.value().getPayload().getOperation(), record.topic());

    handlerFactory.getHandler(record.topic()).process(record.value());

  });

  acknowledgment.acknowledge();
}
 
示例3
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();
    }
}
 
示例4
@Around("execution (@io.micrometer.core.annotation.Timed * *.*(..))")
public Object timedMethod(ProceedingJoinPoint pjp) throws Throwable {
    Method method = ((MethodSignature) pjp.getSignature()).getMethod();
    Timed timed = method.getAnnotation(Timed.class);
    if (timed == null) {
        method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
        timed = method.getAnnotation(Timed.class);
    }

    final String metricName = timed.value().isEmpty() ? DEFAULT_METRIC_NAME : timed.value();
    final boolean stopWhenCompleted = CompletionStage.class.isAssignableFrom(method.getReturnType());

    if (!timed.longTask()) {
        return processWithTimer(pjp, timed, metricName, stopWhenCompleted);
    } else {
        return processWithLongTaskTimer(pjp, timed, metricName, stopWhenCompleted);
    }
}
 
示例5
private Object processWithLongTaskTimer(ProceedingJoinPoint pjp, Timed timed, String metricName, boolean stopWhenCompleted) throws Throwable {

        Optional<LongTaskTimer.Sample> sample = buildLongTaskTimer(pjp, timed, metricName).map(LongTaskTimer::start);

        if (stopWhenCompleted) {
            try {
                return ((CompletionStage<?>) pjp.proceed()).whenComplete((result, throwable) -> sample.ifPresent(this::stopTimer));
            } catch (Exception ex) {
                sample.ifPresent(this::stopTimer);
                throw ex;
            }
        }

        try {
            return pjp.proceed();
        } finally {
            sample.ifPresent(this::stopTimer);
        }
    }
 
示例6
private Set<Timed> annotations(RequestEvent event) {
    final Set<Timed> timed = new HashSet<>();

    final ResourceMethod matchingResourceMethod = event.getUriInfo().getMatchedResourceMethod();
    if (matchingResourceMethod != null) {
        // collect on method level
        timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod()));

        // fallback on class level
        if (timed.isEmpty()) {
            timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod()
                .getDeclaringClass()));
        }
    }
    return timed;
}
 
示例7
@EventHandler
@Override
@Timed
public void onModuleTechnosUpdatedEvent(ModuleTechnosUpdatedEvent event) {
    Optional<ModuleDocument> optModuleDocument = moduleRepository.findById(event.getModuleId());
    if (!optModuleDocument.isPresent()) {
        throw new NotFoundException("Module not found - update impossible - module ID: " + event.getModuleId());
    }
    ModuleDocument moduleDocument = optModuleDocument.get();
    List<TechnoDocument> technoDocuments = technoProjectionRepository.getTechnoDocumentsFromDomainInstances(
            event.getTechnos(), moduleDocument.getDomainKey());
    moduleDocument.setTechnos(technoDocuments);
    moduleDocument.setVersionId(event.getVersionId());

    moduleDocument.extractPropertiesAndSave(moduleRepository);
}
 
示例8
@EventHandler
@Override
@Timed
public void onPlatformModulePropertiesUpdatedEvent(PlatformModulePropertiesUpdatedEvent event) {
    // Tranformation des propriétés du domaine en documents
    final List<AbstractValuedPropertyDocument> abstractValuedProperties = AbstractValuedPropertyDocument.fromAbstractDomainInstances(event.getValuedProperties());

    // Récupération de la plateforme et mise à jour de la version
    Optional<PlatformDocument> optPlatformDocument = minimalPlatformRepository.findById(event.getPlatformId());
    if (!optPlatformDocument.isPresent()) {
        throw new NotFoundException("Platform not found - module properties update impossible - platform ID: " + event.getPlatformId());
    }
    PlatformDocument platformDocument = optPlatformDocument.get();
    platformDocument.setVersionId(event.getPlatformVersionId());

    // Modification des propriétés du module dans la plateforme
    platformDocument.getActiveDeployedModules()
            .filter(currentDeployedModuleDocument -> currentDeployedModuleDocument.getPropertiesPath().equals(event.getPropertiesPath()))
            .findAny().ifPresent(deployedModuleDocument -> {
        updateDeployedModuleVersionId(event.getPropertiesVersionId(), deployedModuleDocument);
        completePropertiesWithMustacheContent(abstractValuedProperties, deployedModuleDocument);
    });

    platformDocument.buildInstancesModelAndSave(minimalPlatformRepository);
}
 
示例9
@EventHandler
@Override
@Timed
public void onPlatformPropertiesUpdatedEvent(PlatformPropertiesUpdatedEvent event) {

    // Transform the properties into documents
    List<ValuedPropertyDocument> valuedProperties = event.getValuedProperties()
            .stream()
            .map(ValuedPropertyDocument::new)
            .collect(Collectors.toList());

    // Retrieve platform

    Optional<PlatformDocument> optPlatformDocument = minimalPlatformRepository.findById(event.getPlatformId());
    if (!optPlatformDocument.isPresent()) {
        throw new NotFoundException("Platform not found - platform properties update impossible - platform ID: " + event.getPlatformId());
    }
    PlatformDocument platformDocument = optPlatformDocument.get();

    // Update platform information
    platformDocument.setVersionId(event.getPlatformVersionId());
    platformDocument.setGlobalProperties(valuedProperties);
    platformDocument.setGlobalPropertiesVersionId(event.getGlobalPropertiesVersionId());
    platformDocument.buildInstancesModelAndSave(minimalPlatformRepository);
}
 
示例10
@QueryHandler
@Override
@Timed
public Optional<String> onGetPlatformIdFromEvents(GetPlatformIdFromEvents query) {
    // On recherche dans TOUS les événements un PlatformEventWithPayload ayant la bonne clef.
    // On se protège en terme de perfs en n'effectuant cette recherche que sur les 7 derniers jours.
    Instant todayLastWeek = Instant.ofEpochSecond(System.currentTimeMillis() / 1000 - 7 * 24 * 60 * 60);
    Stream<? extends TrackedEventMessage<?>> abstractEventStream = eventStorageEngine.readEvents(eventStorageEngine.createTokenAt(todayLastWeek), false);
    Optional<PlatformDeletedEvent> lastMatchingPlatformEvent = abstractEventStream
            .map(GenericTrackedDomainEventMessage.class::cast)
            .filter(msg -> PlatformAggregate.class.getSimpleName().equals(msg.getType()))
            .map(MessageDecorator::getPayload)
            // On part du principe qu'une plateforme à restaurer a forcément été supprimée,
            // on peut donc n'effectuer la recherche que sur l'évènement `PlatformDeletedEvent`
            .filter(PlatformDeletedEvent.class::isInstance)
            .map(PlatformDeletedEvent.class::cast)
            .filter(platformEvent -> platformEvent.getPlatformKey().getApplicationName().equalsIgnoreCase(query.getPlatformKey().getApplicationName()) &&
                    platformEvent.getPlatformKey().getPlatformName().equalsIgnoreCase(query.getPlatformKey().getPlatformName()))
            .reduce((first, second) -> second); // On récupère le dernier élément
    return lastMatchingPlatformEvent.map(PlatformDeletedEvent::getPlatformId);
}
 
示例11
@QueryHandler
@Override
@Timed
public List<String> onGetInstancesModelQuery(GetInstancesModelQuery query) {
    PlatformKeyDocument platformKeyDocument = new PlatformKeyDocument(query.getPlatformKey());
    final Optional<PlatformDocument> platformDocument = platformRepository
            .findModuleByPropertiesPath(platformKeyDocument, query.getPropertiesPath());

    return platformDocument
            .map(PlatformDocument::getActiveDeployedModules)
            .orElse(Stream.empty())
            .flatMap(deployedModuleDocument -> Optional.ofNullable(deployedModuleDocument.getInstancesModel())
                    .orElseGet(Collections::emptyList)
                    .stream())
            .collect(Collectors.toList());
}
 
示例12
@GetMapping("/people")
@Timed(value = "people.all", longTask = true)
public List<String> listPeople() throws InterruptedException {
    int seconds2Sleep = SECURE_RANDOM.nextInt(500);
    System.out.println(seconds2Sleep);
    TimeUnit.MILLISECONDS.sleep(seconds2Sleep);
    return Arrays.asList("Jim", "Tom", "Tim");
}
 
示例13
/**
  * PUT /users: update an existing user
  *
  * @param userDto entity to save
  * @return the ResponseEntity with status 200 (OK) and with body the updated user
  * or the ResponseEntity with status 404 (NOT FOUND) if the user was not found
  * @throws IllegalArgumentException when any given argument is invalid
  */
 @PutMapping
 @Timed
 Mono<ResponseEntity<UserDto>> update(@Valid @RequestBody UserDto userDto) {
   LOGGER.debug("REST request update an existing user : {}", userDto);

   if (Objects.isNull(userDto.getId())) {
     throw new IllegalArgumentException("The provided user should have an id");
   }

   //@formatter:off
   return userService.update(userDto)
				  .map(updatedUser -> ResponseEntity.ok().body(updatedUser));
//@formatter:on
 }
 
示例14
/**
  * DELETE /users/:userId: delete an existing user
  *
  * @param userId id of the user
  * @return the ResponseEntity with status 200 (OK) if deleted
  * or the ResponseEntity with status 404 (NOT FOUND) if the user was not found
  * @throws IllegalArgumentException when any given argument is invalid
  */
 @DeleteMapping("/{userId}")
 @Timed
 Mono<ResponseEntity<Void>> deleteById(@PathVariable("userId") String userId) {
   LOGGER.debug("REST request to delete the user with id : {}", userId);

   if (StringUtils.isEmpty(userId)) {
     throw new IllegalArgumentException("The provided id is invalid");
   }

   //@formatter:off
   return userService.deleteById(userId)
				  .map(v -> ResponseEntity.ok().build());
//@formatter:on
 }
 
示例15
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());
}
 
示例16
@Timed(value = "bootstrap", description = "Timing information for the bootstrapping event.")
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
  // bootstrap only for root context, not for child contexts
  if (event.getApplicationContext().getParent() != null) {
    return;
  }

  bootstrapper.bootstrap(event);

  // prevent memory leak
  SecurityContextHolder.clearContext();
}
 
示例17
@QueryHandler
@Override
@Timed
public List<AbstractPropertyView> onGetTechnoPropertiesQuery(GetTechnoPropertiesQuery query) {
    KeyDocument keyDocument = new KeyDocument(query.getTechnoKey());
    TechnoDocument technoDocument = technoRepository.findPropertiesByTechnoKey(keyDocument);
    return AbstractPropertyDocument.toViews(technoDocument.getProperties());
}
 
示例18
@QueryHandler
@Override
@Timed
public List<String> onGetTechnoVersionsQuery(GetTechnoVersionsQuery query) {
    return technoRepository.findVersionsByKeyName(query.getTechnoName())
            .stream()
            .map(TechnoDocument::getKey)
            .map(KeyDocument::getVersion)
            .collect(Collectors.toList());
}
 
示例19
@QueryHandler
@Override
@Timed
public Optional<TechnoView> onGetTechnoQuery(GetTechnoQuery query) {
    KeyDocument keyDocument = new KeyDocument(query.getTechnoKey());
    return technoRepository.findOptionalTechnoByKey(keyDocument)
            .map(TechnoDocument::toTechnoView);
}
 
示例20
private Set<Timed> annotations(Object handler) {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Set<Timed> timed = TimedUtils.findTimedAnnotations(handlerMethod.getMethod());
        if (timed.isEmpty()) {
            return TimedUtils.findTimedAnnotations(handlerMethod.getBeanType());
        }
        return timed;
    }
    return Collections.emptySet();
}
 
示例21
/*** EVENT HANDLERS ***/

    @EventHandler
    @Override
    @Timed
    public void onTechnoCreatedEvent(TechnoCreatedEvent event) {
        TechnoDocument technoDocument = new TechnoDocument(event.getTechnoId(), event.getTechno());
        technoDocument.extractPropertiesAndSave(technoRepository);
    }
 
示例22
/**
 * Create a timer builder from a {@link Timed} annotation.
 *
 * @param timed The annotation instance to base a new timer on.
 * @return This builder.
 */
static Builder builder(Timed timed) {
    if (!timed.longTask()) {
        throw new IllegalArgumentException("Cannot build a long task timer from a @Timed annotation that is not marked as a long task");
    }

    if (timed.value().isEmpty()) {
        throw new IllegalArgumentException("Long tasks instrumented with @Timed require the value attribute to be non-empty");
    }

    return new Builder(timed.value())
            .tags(timed.extraTags())
            .description(timed.description().isEmpty() ? null : timed.description());
}
 
示例23
/**
 * Create a timer builder from a {@link Timed} annotation.
 *
 * @param timed       The annotation instance to base a new timer on.
 * @param defaultName A default name to use in the event that the value attribute is empty.
 * @return This builder.
 */
static Builder builder(Timed timed, String defaultName) {
    if (timed.longTask() && timed.value().isEmpty()) {
        // the user MUST name long task timers, we don't lump them in with regular
        // timers with the same name
        throw new IllegalArgumentException("Long tasks instrumented with @Timed require the value attribute to be non-empty");
    }

    return new Builder(timed.value().isEmpty() ? defaultName : timed.value())
            .tags(timed.extraTags())
            .description(timed.description().isEmpty() ? null : timed.description())
            .publishPercentileHistogram(timed.histogram())
            .publishPercentiles(timed.percentiles().length > 0 ? timed.percentiles() : null);
}
 
示例24
private void record(ProceedingJoinPoint pjp, Timed timed, String metricName, Timer.Sample sample, String exceptionClass) {
    try {
        sample.stop(Timer.builder(metricName)
                .description(timed.description().isEmpty() ? null : timed.description())
                .tags(timed.extraTags())
                .tags(EXCEPTION_TAG, exceptionClass)
                .tags(tagsBasedOnJoinPoint.apply(pjp))
                .publishPercentileHistogram(timed.histogram())
                .publishPercentiles(timed.percentiles().length == 0 ? null : timed.percentiles())
                .register(registry));
    } catch (Exception e) {
        // ignoring on purpose
    }
}
 
示例25
/**
 * Secure long task timer creation - it should not disrupt the application flow in case of exception
 */
private Optional<LongTaskTimer> buildLongTaskTimer(ProceedingJoinPoint pjp, Timed timed, String metricName) {
    try {
        return Optional.of(LongTaskTimer.builder(metricName)
                                   .description(timed.description().isEmpty() ? null : timed.description())
                                   .tags(timed.extraTags())
                                   .tags(tagsBasedOnJoinPoint.apply(pjp))
                                   .register(registry));
    } catch (Exception e) {
        return Optional.empty();
    }
}
 
示例26
@QueryHandler
@Override
@Timed
public List<TemplateView> onGetTemplatesQuery(GetTemplatesQuery query) {
    TemplateContainer.Key technoKey = query.getTechnoKey();
    return technoRepository.findTemplatesByTechnoKey(new KeyDocument(technoKey))
            .map(technoDocument -> technoDocument.getTemplates()
                    .stream()
                    .map(templateDocument -> templateDocument.toTemplateView(technoKey))
                    .collect(Collectors.toList()))
            .orElseGet(Collections::emptyList);
}
 
示例27
Set<Timed> findTimedAnnotations(AnnotatedElement element) {
    Timed t = annotationFinder.findAnnotation(element, Timed.class);
    if (t != null)
        return Collections.singleton(t);

    TimedSet ts = annotationFinder.findAnnotation(element, TimedSet.class);
    if (ts != null) {
        return Arrays.stream(ts.value()).collect(Collectors.toSet());
    }

    return Collections.emptySet();
}
 
示例28
@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;
    }
}
 
示例29
private Set<LongTaskTimer> longTaskTimers(Set<Timed> timed, RequestEvent event) {
    return timed.stream()
        .filter(Timed::longTask)
        .map(LongTaskTimer::builder)
        .map(b -> b.tags(tagsProvider.httpLongRequestTags(event)).register(registry))
        .collect(Collectors.toSet());
}
 
示例30
@QueryHandler
@Override
@Timed
public List<String> onGetTechnosNameQuery(GetTechnosNameQuery query) {
    final DistinctIterable<String> iterable = mongoTemplate.getCollection(TECHNO).distinct("key.name", String.class);
    return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
}