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");
}
}