SpirngBoot中使用Micrometer

SpirngBoot中使用Micrometer

SpringBoot中的spring-boot-starter-actuator依赖已经集成了对Micrometer的支持,其中的metrics端点的很多功能就是通过Micrometer实现的,prometheus端点默认也是开启支持的,实际上actuator依赖的spring-boot-actuator-autoconfigure中集成了对很多框架的开箱即用的API。

其中prometheus包中集成了对Prometheus的支持,使得使用了actuator可以轻易地让项目暴露出prometheus端点,作为Prometheus收集数据的客户端,Prometheus(服务端软件)可以通过此端点收集应用中Micrometer的度量数据。

我们先引入spring-boot-starter-actuator和spring-boot-starter-web,实现一个Counter和Timer作为示例。依赖:

<dependencyManagement>
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-dependencies</artifactId>
              <version>2.1.0.RELEASE</version>
              <type>pom</type>
              <scope>import</scope>
          </dependency>
      </dependencies>
  </dependencyManagement>
  <dependencies>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
      </dependency>
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.16.22</version>
      </dependency>
<dependency>
          <groupId>io.micrometer</groupId>
          <artifactId>micrometer-registry-prometheus</artifactId>
          <version>1.1.0</version>
      </dependency>
  </dependencies>

接着编写一个下单接口和一个消息发送模块,模拟用户下单之后向用户发送消息:

//实体
@Data
public class Message {

        private String orderId;
        private Long userId;
        private String content;
    }

    @Data
    public class Order {

        private String orderId;
        private Long userId;
        private Integer amount;
        private LocalDateTime createTime;
    }

    //控制器和服务类
    @RestController
    public class OrderController {

        @Autowired
        private OrderService orderService;

        @PostMapping(value = "/order")
        public ResponseEntity<Boolean> createOrder(@RequestBody Order order){
            return ResponseEntity.ok(orderService.createOrder(order));
        }
    }

    @Slf4j
    @Service
    public class OrderService {

        private static final Random R = new Random();

        @Autowired
        private MessageService messageService;

        public Boolean createOrder(Order order) {
            //模拟下单
            try {
                int ms = R.nextInt(50) + 50;
                TimeUnit.MILLISECONDS.sleep(ms);
                log.info("保存订单模拟耗时{}毫秒...", ms);
            } catch (Exception e) {
                //no-op
            }
            //记录下单总数
            Metrics.counter("order.count", "order.channel", order.getChannel()).increment();
            //发送消息
            Message message = new Message();
            message.setContent("模拟短信...");
            message.setOrderId(order.getOrderId());
            message.setUserId(order.getUserId());
            messageService.sendMessage(message);
            return true;
        }
    }

    @Slf4j
    @Service
    public class MessageService implements InitializingBean {

        private static final BlockingQueue<Message> QUEUE = new ArrayBlockingQueue<>(500);
        private static BlockingQueue<Message> REAL_QUEUE;
        private static final Executor EXECUTOR = Executors.newSingleThreadExecutor();
        private static final Random R = new Random();

        static {
            REAL_QUEUE = Metrics.gauge("message.gauge", Tags.of("message.gauge", "message.queue.size"), QUEUE, Collection::size);
        }

        public void sendMessage(Message message) {
            try {
                REAL_QUEUE.put(message);
            } catch (InterruptedException e) {
                //no-op
            }
        }

        @Override
        public void afterPropertiesSet() throws Exception {
            EXECUTOR.execute(() -> {
                while (true) {
                    try {
                        Message message = REAL_QUEUE.take();
                        log.info("模拟发送短信,orderId:{},userId:{},内容:{},耗时:{}毫秒", message.getOrderId(), message.getUserId(),
                                message.getContent(), R.nextInt(50));
                    } catch (Exception e) {
                        throw new IllegalStateException(e);
                    }
                }
            });
        }
    }

    //切面类
    @Component
    @Aspect
    public class TimerAspect {

        @Around(value = "execution(* club.throwable.smp.service.*Service.*(..))")
        public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            Timer timer = Metrics.timer("method.cost.time", "method.name", method.getName());
            ThrowableHolder holder = new ThrowableHolder();
            Object result = timer.recordCallable(() -> {
                try {
                    return joinPoint.proceed();
                } catch (Throwable e) {
                    holder.throwable = e;
                }
                return null;
            });
            if (null != holder.throwable) {
                throw holder.throwable;
            }
            return result;
        }

        private class ThrowableHolder {

            Throwable throwable;
        }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itlanmao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值