1.高并发解决方法

发布时间 2023-09-19 15:17:10作者: 壹索007
 /**
     * 查询订单详情 (GET)
     */
    @RequestMapping(value = "/online/queryOrderInfo", produces = "application/json")
    public RestResult queryOrderInfo(HttpServletRequest request, Integer id) {
        String uriStr=request.getRequestURI();
        Object result=gatewayService.loadLalancing("id",id, uriStr);
        if(result==null){
            return RestResult.failure();
        }
        return RestResult.success().data(result);
    }

    /**
     * 根据机房Id查询机房名称 (GET)
     */
    @RequestMapping(value = "/online/queryRegionName", produces = "application/json")
    public Object queryRegionName(HttpServletRequest request, Integer regionId) {
        String uriStr=request.getRequestURI();
        Object result=gatewayService.loadLalancing("regionId",regionId,uriStr);
        if(result==null){
            return RestResult.failure();
        }
        ObjectNode node=new ObjectMapper().createObjectNode();
        node.put("code",200);
        node.put("msg","ok");
        node.put("requestId",LogUtil.getRequestId());
        node.put("data", result.toString());
        return node;
    }

    /**
     * 订单优惠券抵扣 (POST json)
     */
    @RequestMapping(value = "/online/voucher/deduct", produces = "application/json")
    public Object deduct(HttpServletRequest request,@RequestBody VoucherDeductDTO param) {
        String uriStr=request.getRequestURI();
        Object result=gatewayService.loadLalancing("deduct",param,uriStr).toString();
        if(result==null){
            return RestResult.failure();
        }
        ObjectNode node=new ObjectMapper().createObjectNode();
        node.put("code",200);
        node.put("msg",result.toString());
        node.put("requestId",LogUtil.getRequestId());
        return node;
    }

    /**
     * 基于Redis实现漏桶限流算法,并在API调用上体现
     */
    @Autowired
    private FunnelRateLimiter funnelRateLimiter;
   @RequestMapping(value = "/online/listUpstreamInfo", produces = "application/json")
    public ResponseEntity listUpstreamInfo(HttpServletRequest request, HttpServletResponse response) {
        //ObjectNode node = new ObjectMapper().createObjectNode();
        boolean isAllow=funnelRateLimiter.tryAcquire();
       Map responseMap = new HashMap();
       ResponseEntity responseEntity =null;
       if (isAllow) {
            responseMap.put("code", "200");
            responseMap.put("msg", "ok");
            responseMap.put("requestId", LogUtil.getRequestId());
            responseMap.put("data", gatewayService.getUpstreamInfo().toString());
            responseEntity = new ResponseEntity(responseMap, HttpStatus.OK);
        } else {
            responseMap.put("code", "429");
            responseMap.put("msg", "对不起, 系统压力过大, 请稍后再试!");
            responseMap.put("requestId", LogUtil.getRequestId());
            responseEntity = new ResponseEntity(responseMap,HttpStatus.TOO_MANY_REQUESTS);
        }
       return responseEntity;
    }