由于需求,需要在网关层做一些参数的替换,特此记录一下,以下方式只针对GET请求
import com.netflix.zuul.ZuulFilter;import com.netflix.zuul.context.RequestContext;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;/** * 过滤参数 * * @author * 2019-5-17 10:01 */@Componentpublic class ParametersFilter extends ZuulFilter { private static final Logger LOGGER = LoggerFactory.getLogger(ParametersFilter.class); private static final String KEY = "PARAMETER_FILTER_KEY"; @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return 9; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { // 获取到request RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); try { //是否拦截 // todo //防止错误重试多次转换 Boolean isConver = (Boolean) request.getAttribute(KEY); if (isConver != null && isConver) { return null; } String method = request.getMethod(); LOGGER.info("将对请求进行替换, 方法为{}, url = {}", method, request.getRequestURI()); // get方法 if ("GET".equals(method.toUpperCase())) { //获取参数 MapparameterMap = request.getParameterMap(); if (parameterMap == null) { return null; } //替换,业务逻辑 Map > requestQueryParams = ctx.getRequestQueryParams(); if (requestQueryParams == null) { requestQueryParams = new HashMap<>(parameterMap.size() * 2); } for (String key : parameterMap.keySet()) { String[] values = parameterMap.get(key); List valueList = new LinkedList<>(); for (String value : values) { valueList.add(change(value)); } requestQueryParams.put(key, valueList); } //重新写入参数 ctx.setRequestQueryParams(requestQueryParams); LOGGER.info("转译完成, url = {}", request.getRequestURI()); } } catch (Exception e) { LOGGER.error("参数替换异常:{}", e); } finally { request.setAttribute(KEY, true); } return null; } /** * 替换 * * @param data 数据 * @return 转译后数据 */ private String change(String data) { // todo return data; }}