首页 > 编程知识 正文

springcloud中网关,springcloud权限认证

时间:2023-05-04 02:15:22 阅读:144475 作者:4792

1.APP.yml配置

spring : cloud : gateway : routes 3360-id : remote addr _ routeuri :3358 localhost :8080 path

predicates :当满足predicates中的条件时,即path路径为/test时启用网关。

uri :跳至uri (请注意,此处的uri不是url )。

filters:filters下的RewritePath将路径重定义从/test更改为/add。 如果不添加此处,path拥有的路径将自动连接在uri后面。

最后一行的- Test是文件名,写在下面

2 .实现网关

的主要实现由三部分组成:过滤器、Mono和网关过滤器。

分析:

GatewayFilterFactory :上面-Test的文件名这里的名称是TestGatewayFilterFactory,当网关匹配时自动忽略后续的GatewayFilterFactory,在测试中进行测试

@ component @ slf4j @ lazypublicclasstestgatewayfilterfactoryextendsabstractgatewayfiltertestfilterfactory { @ autowiredtestestfiltertetertetfififite (} }过滤器)相当于中间层

@ componentpublicclasstestfilterimplementsgatewayfilter,ordered { @ autowiredtestmonotestmono; @ overridepublicmonovoidfilter (serverwebexchangeexchange,GatewayFilterChain chain ) returntestmono.testmono ) exchange } (}} Mono )主要逻辑实现层

主要实现由testMono协调,从网关转发的请求的分析可以在该方法内实现,如果有解码的需要,在该方法内添加方法即可。

requestDecorator :此方法用于转换请求,代码将post请求转换为get。

urlEncodeUTF8 :在此代码实现中用于解析开机自检请求的参数将与get请求合并。

响应解码器:网关处理完成后返回的结果在此包装并输出,如果有加密,则在此方法中执行。

@ component @ sl F4 jpublicclasstestmono//主要方法publicmonovoidtestmono (serverwebexchangeexchange,GatewayFilterChain chain ) ) serverhttpresponseresponse=exchange.getresponse (; returndatabufferutils.join (request.getbody ().flatmap )数据缓冲器- { databufferutils.retain )数据缓冲器); byte [ ] bytes=new byte [ data buffer.readable bytecount (); 数据缓冲器. read (bytes ); //释放内存databufferutils.release (数据缓冲器)的字符串体=new string (bytes,StandardCharsets.UTF_8); URI url=request.getURI (; log.info(url: )、URL );

JSONObject bodyJson = JSON.parseObject(body); JSONObject innerBody = bodyJson.getJSONObject("BODY"); return chain.filter(exchange.mutate().request(requestDecorator(request, innerBody)).response(responseDecorator(response)).build()); }); }//将post请求转换成get(若是get可连同下面的方法省略) private static ServerHttpRequestDecorator requestDecorator(ServerHttpRequest request, JSONObject body) { return new ServerHttpRequestDecorator(request) { // 重新设置http method @Override public HttpMethod getMethod() { return HttpMethod.GET; } @Override public String getMethodValue() { return "GET"; } // 转换请求参数 @Override public URI getURI() { String params = urlEncodeUTF8(body); return URI.create(request.getURI() + "?" + params); } }; } /** * 转换urlparam *(post请求忽略) * @param jsonObject * @return */ private static String urlEncodeUTF8(JSONObject jsonObject) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(String.format("%s=%s", entry.getKey(), entry.getValue() )); } log.info("format param: {}", sb); return sb.toString(); }//网关转出 private ServerHttpResponseDecorator responseDecorator (ServerHttpResponse response) { return new ServerHttpResponseDecorator(response) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { if (body instanceof Flux) { Flux<? extends DataBuffer> flux = Flux.from(body); return super.writeWith(flux.buffer().map(dataBuffers -> { DataBufferFactory dataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT); StringBuilder sb = new StringBuilder(""); DataBuffer join = dataBufferFactory.join(dataBuffers); byte[] bytes = new byte[join.readableByteCount()]; join.read(bytes); DataBufferUtils.release(join); String s = new String(bytes, StandardCharsets.UTF_8); sb.append(s); //去掉字符串最外层的[] //sb.deleteCharAt(0).deleteCharAt(sb.length() - 1);` // 构造返回报文 JSONObject jsonBody = JSON.parseObject(sb.toString(), JSONObject.class, Feature.OrderedField); String content = JSON.toJSONString(jsonBody, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames, SerializerFeature.PrettyFormat); byte[] contentByte = content.getBytes(); // 重置content-length response.getHeaders().setContentLength(contentByte.length); return response.bufferFactory().wrap(contentByte); })); } return super.writeWith(body); } }; }}

Spring cloud gateway学习地址:Spring Cloud Gateway 2.1.0 中文官网文档 - 云+社区 - 腾讯云

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。