大数据量高并发时如何通过请求的批量处理进行限流?

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

  1. 实例
@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 reql = new LinkedBlockingQueue<>(5000);

    static class Req {
        private String cmd;
        CompletableFuture 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 batch (List reql) {
        Map 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 requl = new ArrayList<>();
        reql.forEach(req -> {
            try{requl.add(reql.take());} catch (Exception e) {e.printStackTrace();}
        });
        Map respm = batch(requl);
        requl.forEach(req -> req.ft.complete(respm.get(req.cmd)));
    }

你可能感兴趣的:(java,spring,cloud)