Java 实现一个性能计数器

这是一个简单的Metrics类实现,用于统计接口的响应时间和时间戳。Metrics类包含一个定时任务,每隔固定时间输出接口的最大响应时间和请求次数。在UserController中,通过login方法模拟了接口调用,并使用Metrics记录性能数据。
摘要由CSDN通过智能技术生成

1.0版本,最小原型

/**
 * 统计类
 */
public class Metrics {
    /**
     * 响应时间,key为接口名称,value为时间集合
     */
    private Map<String, List<Double>> responseTimes = new HashMap<>();

    /**
     * 时间戳,key为接口名称,value为时间集合
     */
    private Map<String, List<Double>> timestamps = new HashMap<>();

    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 记录响应时间
     *
     * @param apiName      接口名称
     * @param responseTime 响应时间
     */
    public void recordResponseTimes(String apiName, Double responseTime) {
        responseTimes.putIfAbsent(apiName, new ArrayList<>());
        responseTimes.get(apiName).add(responseTime);
    }

    /**
     * 记录时间戳
     *
     * @param apiName   接口名称
     * @param timestamp 时间戳
     */
    public void recordTimestamp(String apiName, Double timestamp) {
        timestamps.putIfAbsent(apiName, new ArrayList<>());
        timestamps.get(apiName).add(timestamp);
    }

    public void startRepeatedReport(long period, TimeUnit unit) {
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                Map<String, Map<String, Double>> stats = new HashMap<>();
                for (Map.Entry<String, List<Double>> entry : responseTimes.entrySet()) {
                    String apiName = entry.getKey();
                    List<Double> apiRespTimes = entry.getValue();
                    stats.putIfAbsent(apiName,new HashMap<>());
                    // 接口最大响应时间
                    stats.get(apiName).put("max", Collections.max(apiRespTimes));
                }
                for (Map.Entry<String, List<Double>> entry : timestamps.entrySet()) {
                    String apiName = entry.getKey();
                    List<Double> apiTimestamp = entry.getValue();
                    stats.putIfAbsent(apiName,new HashMap<>());
                    // 接口请求次数
                    stats.get(apiName).put("count", (double) apiTimestamp.size());
                }
                System.out.println(stats);
            }
        }, 0, period, unit);
    }

}



public class UserController {

    private Metrics metrics = new Metrics();

    public UserController() {
        metrics.startRepeatedReport(6, SECONDS);
    }

    public void login(String username, String password){
        long timestamp = System.currentTimeMillis();
        metrics.recordTimestamp("login", (double) timestamp);
        // 业务逻辑省略
        try {
            Thread.sleep(new Random().nextInt(9000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long respTime = System.currentTimeMillis() - timestamp;
        metrics.recordResponseTimes("login", (double) respTime);

    }
}



public class Test {
    public static void main(String[] args) {
        UserController userController = new UserController();
        userController.login("1","1");
        userController.login("2","2");
        userController.login("3","3");

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值