当前位置: 首页 > 科技观察

你知道SpringCloud提供的网关实现吗?

时间:2023-03-19 22:59:28 科技观察

环境:SpringBoot2.5.13SpringCloudGateway提供了一个名为ProxyExchange的实用对象。您可以将它用作常规SpringWeb处理程序中的方法参数。它通过HTTP谓词的镜像方法支持基本的下游HTTP交换。在MVC中它也支持通过forward()方法转发给本地处理程序。要使用ProxyExchange,需要在类路径中包含正确的模块(spring-cloud-gateway-mvc(3.1.5)或spring-cloud-gateway-webflux)。以下MVC示例将对/test下游的请求代理到远程服务器:@RestController@SpringBootApplicationpublicclassGatewaySampleApplication{@Value("${remote.home}")@GetMapping("/test")公共ResponseEntityproxy(ProxyExchangeproxy)throwsException{returnproxy.uri(home.toString()+"/image/png").get();}}以下示例对Webflux执行相同的操作:@RestController@SpringBootApplicationpublicclassGatewaySampleApplication{@Value("${remote.home}")privateURIhome;@GetMapping("/test")publicMono>proxy(ProxyExchangeproxy)throwsException{returnproxy.uri(home.toString()+"/image/png").get();ProxyExchange上的便捷方法,使处理程序方法能够发现和增强传入请求的URI路径。例如,您可能希望提取路径末尾的元素并将其传递到下游:@GetMapping("/proxy/path/**")publicResponseEntityproxyPath(ProxyExchangeproxy)throwsException{//如果这里请求/proxy/path/666,那么这里path=666Stringpath=proxy.path("/proxy/path/");returnproxy.uri(home.toString()+"/foos/"+path).get();}SpringMVC和Webflux的所有特性都可用于网关处理程序方法。因此,可以注入请求标头和查询参数,例如,可以使用映射注释中的声明来约束传入请求。如下:目标服务接口@RestController@RequestMapping("/business")publicclassBusinessController{@PostMapping("/index")publicObjectindex(@RequestBodyMapbody){System.out.println("业务接口接收到的内容:"+body);Mapresult=newHashMap<>();result.put("代码",0);result.put("data","业务处理成功-"+LocalDateTime.now().getNano());result.put("消息","成功");返回结果;}}网关服务接口@RestController@RequestMapping("/proxy/api")publicclassGatewayController{@GetMapping("")publicObjectorder(@RequestHeader("token")Stringtoken,Integerid,ProxyExchange>交换){System.out.println("token="+token+",id="+id);Mapbody=newHashMap<>();body.put("id",id);body.put("代币",代币);返回exchange.uri("http://localhost:9000/business/index").body(body).post();}}调用结果Postman请求控制您还可以使用ProxyExchange的header()方法添加一个headerexchange.uri("http://localhost:9000/business/index").header("key","123123").body(body).post();您还可以通过向get()方法(以及其他方法)添加映射器来操作响应标头(以及响应中的任何其他内容)。mapper是一个Function,它接收传入的ResponseEntity并将其转换为传出的ResponseEntity,如下所示:exchange.uri("http://localhost:9000/business/index").header("key","123123").body(body).post(result->{System.out.println("ResposneHeader:"+result.getHeaders());returnResponseEntity.ok("success");});对于“敏感”标头(默认情况下是cookie和授权)和“代理”(x-forward-*)标头,它们不会传递到下游。比如:当我们的请求中有AuthorizationrequestHeader信息时,默认是不会传递给下游的。这是默认行为并且有cookie。我们可以通过修改配置文件spring:cloud:gateway:proxy:sensitive:-''Done!!!