世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
- 实例
@Controller
public class MultiRequestDemo {
@GetMapping("/pg/{id}")
public String pg (@PathVariable("id") String id) {
return id;
}
@GetMapping("/get")
@ResponseBody
public String get(String nm) {
Resp resp = req(nm);
return resp.re;
}
private static LinkedBlockingQueue<Req> reql = new LinkedBlockingQueue<>(5000);
static class Req {
private String cmd;
CompletableFuture<Resp> ft;
}
static class Resp {
private String cmd;
private String re;
}
public Resp req (String cmd) {
try {
Req req = new Req();
req.cmd = cmd;
req.ft = new CompletableFuture<>();
reql.put(req);
return req.ft.get();
} catch (Exception e) {e.printStackTrace();}
return null;
}
public Map<String, Resp> batch (List<Req> reql) {
Map<String, Resp> respm = new HashMap<>(16);
reql.forEach(req -> {
Resp resp = new Resp();
resp.cmd = req.cmd;
int ran = new Random().nextInt(5);
resp.re = resp.cmd + ran;
respm.put(resp.cmd, resp);
});
return respm;
}
// 每5秒处理一次请求
@PostConstruct
@Scheduled(fixedRate = 5000)
public void doIt () {
if (reql.size() == 0) {return;}
List<Req> requl = new ArrayList<>();
reql.forEach(req -> {
try{requl.add(reql.take());} catch (Exception e) {e.printStackTrace();}
});
Map<String, Resp> respm = batch(requl);
requl.forEach(req -> req.ft.complete(respm.get(req.cmd)));
}