最近换的部门,对接口性能要求非常高,单台机器的qps高峰大概在300左右,导致我非常谨慎,各种catch和兜底
遇见个场景,2个线程处理任务,必须都在10ms内返回(一共10ms),如果返回不了,就不处理;
下面是一代代码demo:
CompletableFuture<Map<String, Object>> localFuture = CompletableFuture.supplyAsync(() -> {
// 模拟一个耗时的操作
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 返回一个 Map 对象
// 返回一个 Map 对象
Map<String, Object> map = new HashMap<>();
map.put("1",1);
return map;
});
CompletableFuture<Map<String, Object>> redisFuture = CompletableFuture.supplyAsync(() -> {
// 模拟一个耗时的操作
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 返回一个 Map 对象
Map<String, Object> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
return map;
});
CompletableFuture<Void> allFuture = CompletableFuture.allOf(localFuture, redisFuture);
try {
allFuture.get(5, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> localExistKeysMapResult = localFuture.getNow(new HashMap<>());
Map<String, Object> redisExistKeysMapResult = redisFuture.getNow(new HashMap<>());
System.out.println("Result from localFuture: " + localExistKeysMapResult);
System.out.println("Result from redisFuture: " + redisExistKeysMapResult);