springboot(41) : 转发所有请求及鉴权

maven依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
            <scope>provided</scope>
        </dependency>

controller


import com.alibaba.fastjson.JSONObject;
import com.alibaba.gts.flm.authorize.center.biz.core.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class AuthorizeController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String LOG_PATTERN = System.lineSeparator() + "    ip:{}" + System.lineSeparator() + "    method:{}" + System.lineSeparator() + "    url:{}" + System.lineSeparator() + "    req:{}" + System.lineSeparator() + "    header:{}" + System.lineSeparator() + "    resp:{}" + System.lineSeparator() + "    time:{}" + System.lineSeparator() + "    req.size:{}" + System.lineSeparator() + "    resp.size:{}" + System.lineSeparator();

    @RequestMapping("/**")
    public Object handle(HttpServletRequest request) throws Exception {
        String requestURI = request.getRequestURI();
        // 鉴权

        // 转发
        return forward(request);
    }

    private Object forward(HttpServletRequest request) throws Exception {
        String req = ParamUtil.getParam(request);
        Enumeration<String> parameterNames = request.getParameterNames();
        Enumeration<String> headerNames = request.getHeaderNames();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();

        String proxyUri = requestURI;
        StringBuffer params = new StringBuffer();
        while (parameterNames.hasMoreElements()) {
            String s = parameterNames.nextElement();
            params.append(s).append("=").append(request.getParameter(s)).append("&");
        }
        if (params.length() > 0) {
            params.delete(params.length() - 1, params.length());
            proxyUri += "?" + params;
        }

        HttpHeaders headers = new HttpHeaders();
        Map<String, String> headerParams = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            headers.set(s, request.getHeader(s));
            headerParams.put(s, request.getHeader(s));
        }

        HttpEntity<String> proxyRequest = null;
        if (req != null && req.length() > 3) {
            proxyRequest = new HttpEntity<>(req, headers);
        } else {
            proxyRequest = new HttpEntity<>(headers);
        }

        ResponseEntity<Object> result;
        String url = "http://192.168.1.1:" + getPort(requestURI) + proxyUri;
        try {
            long currentTimeMillis = System.currentTimeMillis();
            result = restTemplate.exchange(url, getMethod(method), proxyRequest, Object.class);
            log.info(LOG_PATTERN, request.getRemoteHost(), url, method, smallStr(req), JSONObject.toJSONString(headerParams),
                    smallStr(JSONObject.toJSONString(result.getBody())), getHaoShi(currentTimeMillis),
                    getSize(req), getSize(JSONObject.toJSONString(result.getBody())));
            return result.getBody();
        } catch (Exception e) {
            if (e.getMessage().contains("404")) {
                log.warn("404 uri:{}", requestURI);
            } else {
                log.error("[post]接口调用失败,url:{},req:{},error:{}", url, smallStr(req),
                        ExceptionUtils.getStackTrace(e));
            }
            JSONObject res = new JSONObject();
            res.put("code", 500);
            res.put("success", Boolean.FALSE);
            res.put("msg", e.getMessage());
            return res;
        }
    }

    private String getPort(String uri) {
        return "20003";
    }

    private HttpMethod getMethod(String method) {
        switch (method) {
            case "GET":
                return HttpMethod.GET;
            case "HEAD":
                return HttpMethod.HEAD;
            case "POST":
                return HttpMethod.POST;
            case "PUT":
                return HttpMethod.PUT;
            case "PATCH":
                return HttpMethod.PATCH;
            case "DELETE":
                return HttpMethod.DELETE;
            case "OPTIONS":
                return HttpMethod.OPTIONS;
            case "TRACE":
                return HttpMethod.TRACE;
            default:
                break;
        }
        return null;
    }

    public String smallStr(String str) {
        if (str == null) {
            return null;
        }
        boolean tooLong = str.length() > 1000;
        return tooLong ? str.substring(0, 1000) + " ..." : str;
    }


    /**
     * 计算耗时
     *
     * @param time 开始时间戳(毫秒)
     * @return
     */
    public static String getHaoShi(Long time) {
        long t = System.currentTimeMillis() - time;
        double d7 = t / 1000.0 / 60 / 60 / 24 / 30 / 12 / 100;
        if (d7 > 1) return round(d7, 1) + "纪元";
        double d6 = t / 1000.0 / 60 / 60 / 24 / 30 / 12;
        if (d6 > 1) return round(d6, 1) + "年";
        double d5 = t / 1000.0 / 60 / 60 / 24 / 30;
        if (d5 > 1) return round(d5, 1) + "月";
        double d4 = t / 1000.0 / 60 / 60 / 24;
        if (d4 > 1) return round(d4, 1) + "天";
        double d3 = t / 1000.0 / 60 / 60;
        if (d3 > 1) return round(d3, 1) + "小时";
        double d2 = t / 1000.0 / 60;
        if (d2 > 1) return round(d2, 1) + "分钟";
        double d1 = t / 1000.0;
        if (d1 > 1) return round(d1, 1) + "秒";
        return t + "毫秒";
    }

    /**
     * 计算大小
     *
     * @param str 字符串
     * @return
     */
    public static String getSize(String str) {
        if (str == null) {
            return "-";
        }
        byte[] bytes = str.getBytes();
        int length = bytes.length;
        double d7 = length / Math.pow(1024.0, 7);
        if (d7 > 1) return round(d7, 1) + "ZB";
        double d6 = length / Math.pow(1024.0, 6);
        if (d6 > 1) return round(d6, 1) + "EB";
        double d5 = length / Math.pow(1024.0, 5);
        if (d5 > 1) return round(d5, 1) + "PB";
        double d4 = length / Math.pow(1024.0, 4);
        if (d4 > 1) return round(d4, 1) + "TB";
        double d3 = length / Math.pow(1024.0, 3);
        if (d3 > 1) return round(d3, 1) + "GB";
        double d2 = length / Math.pow(1024.0, 2);
        if (d2 > 1) return round(d2, 1) + "MB";
        double d1 = length / Math.pow(1024.0, 1);
        ;
        if (d1 > 1) return round(d1, 1) + "KB";
        return length + "B";
    }

    public static Double round(Double data, int amount) {
        if (data == null) {
            return null;
        } else {
            double result = (new BigDecimal(data)).setScale(amount, 4).doubleValue();
            return result;
        }
    }
}

ParamUtil 


import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;


public class ParamUtil {


    public static String getParam(HttpServletRequest httpServletRequest) throws Exception {
        //从前端获取输入字节流
        ServletInputStream requestInputStream = httpServletRequest.getInputStream();
        //将字节流转换为字符流,并设置字符编码为utf-8
        InputStreamReader ir = new InputStreamReader(requestInputStream, "utf-8");
        //使用字符缓冲流进行读取
        BufferedReader br = new BufferedReader(ir);
        //开始拼装json字符串
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值