美文网首页
sprinngboot+micrometer+prometheu

sprinngboot+micrometer+prometheu

作者: 莘莘农子 | 来源:发表于2019-05-21 16:27 被阅读0次

    1.pom需要添加的依赖

    2.application.yml的配置内容

    #监控配置

    management:

      security:

    # 仅限于 开发环境可对security进行关闭。

        enabled: false

      metrics:

        export:

          prometheus:

            enabled: true

            step: 1m

            descriptions: true

      web:

        server:

          auto-time-requests: true

      endpoints:

        prometheus:

          id: springmetrics

        web:

          exposure:

            include: health,info,env,prometheus,metrics,httptrace,threaddump,heapdump,springmetrics

    3.代码

    package com.sitech.vehicle.job;

    import com.alibaba.fastjson.JSON;

    import com.alibaba.fastjson.JSONObject;

    import com.sitech.utils.http.HttpRequest;

    import com.sitech.utils.http.HttpResponse;

    import com.sitech.vehicle.config.Constant;

    import com.sitech.vehicle.operator.dto.CommonRequestDTO;

    import com.sitech.vehicle.operator.dto.OperatorCmdDTO;

    import com.sitech.vehicle.tsp.dto.cmd.CmdDTO;

    import com.sitech.vehicle.utils.AESUtils;

    import com.sitech.vehicle.utils.SignatureUtils;

    import io.micrometer.core.instrument.*;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import org.springframework.http.HttpHeaders;

    import org.springframework.http.HttpStatus;

    import org.springframework.http.MediaType;

    import org.springframework.scheduling.annotation.Scheduled;

    import org.springframework.stereotype.Component;

    import java.util.*;

    import java.util.concurrent.atomic.AtomicInteger;

    @Component

    public class ControlCmdJob {

        private static Logger logger = LoggerFactory.getLogger(ControlCmdJob.class);

    List<Tag> init(){

            ArrayList<Tag> list = new ArrayList(){};

            list.add(new ImmutableTag("service", "demo"));

            return list;

        }

        AtomicInteger atomicInteger = new AtomicInteger(0);

        AtomicInteger passCases =  Metrics.gauge("vehicle.cmd.timeout", init(), atomicInteger);

        private String CloudApiUrl = "https://v2n-sv.sitechdev.com";

        private String CloudApiUrl2 = "https://cloud-api.sitechdev.com";

        private String urlCaller4Get(String url) {

            HttpResponse response = HttpRequest.get(url)

                    .execute();

            return response.body();

        }

        private String getCmdParam(String vin) throws Exception {

            Long operatorId = 200353L;

            String sercret = "7b2566668cce3bffc794816548383d03";

            CommonRequestDTO commonRequestDTO = new CommonRequestDTO();

            commonRequestDTO.setOperatorID(operatorId);

            commonRequestDTO.setTimestamp(new Date().getTime());

            OperatorCmdDTO operatorCmdDTO = new OperatorCmdDTO();

            operatorCmdDTO.setVin(vin);

            CmdDTO cmdDTO = new CmdDTO();

            cmdDTO.setCmdName("open_search_lighting");

            operatorCmdDTO.setCmdDTO(cmdDTO);

            String content = JSONObject.toJSONString(operatorCmdDTO);

            String encontent = AESUtils.Encrypt(content, sercret);

            commonRequestDTO.setData(encontent);

            Map<String, String> map = new HashMap<String, String>();

            map.put("operatorID", commonRequestDTO.getOperatorID() + "");

            map.put("data", commonRequestDTO.getData());

            map.put("timestamp", commonRequestDTO.getTimestamp() + "");

            System.out.println("业务参数:" + content);

            System.out.println("加密后: " + encontent);

            try {

                String signature = SignatureUtils.generate(map, sercret);

                System.out.println("签名 : " + signature);

                commonRequestDTO.setSign(signature);

            } catch (Exception e) {

                e.printStackTrace();

            }

            System.out.println(JSONObject.toJSONString(commonRequestDTO));

            return JSONObject.toJSONString(commonRequestDTO);

        }

        @Scheduled(cron = "0/40 * * * * ? ") // 间隔40秒执行,查询车控次数,入库

        public void health() {

            String url = CloudApiUrl + Constant.URL;

            String vin = "XTEVE000000D01001";

            //TODO 调用车控接口,监控车控服务是否异常

            try {

                String responseA=urlCaller4Get(CloudApiUrl2+"/sitechid/authcenter/v2/security/operator-token-build/200353?appKey=7b2566668cce3bffc794816548383d03");

                String token= JSON.parseObject(responseA).getJSONObject("data").getString("operatorToken");

                String operatorId="Operator"+" "+token;

                HttpResponse response = null;

                System.out.println("----"+getCmdParam(vin));

                response = HttpRequest.post(url)

                        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)

                        .header(HttpHeaders.AUTHORIZATION,operatorId)

                        .body(getCmdParam(vin))

                        .execute();

                logger.info("response: " + response.body());

                if (response.getStatus() != HttpStatus.OK.value()){

      passCases.addAndGet(1);

                }

                int cmdStatus=Integer.valueOf(JSONObject.parseObject(response.body()).getJSONObject("data").getString("cmdStatus")).intValue();

                if (response.getStatus() == HttpStatus.OK.value() && cmdStatus==7){

        passCases.addAndGet(1);

                }else{

                  passCases.set(0);

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

    4.prometheus.yml配置

    scrape_configs:

      - job_name: 'prometheus'

        metrics_path: /prometheus

        static_configs:

        - targets: ['localhost:9000']

    5.运行

    本地运行访问:http://localhost:9504/actuator/prometheus  (说明:9504为项目端口号),访问成功如下图:

    访问prometheus:http://localhost:9090  (说明需要本地先启动prometheus的客户端)

    相关文章

      网友评论

          本文标题:sprinngboot+micrometer+prometheu

          本文链接:https://www.haomeiwen.com/subject/xovjzqtx.html