环境:springboot2.3.7 + spring cloud Hoxton.SR9
路由过滤器允许以某种方式修改传入的HTTP请求或输出HTTP响应。路由过滤器的作用域为特定路由。Spring Cloud Gateway包括许多内置的GatewayFilter工厂。
1.AddRequestHeader 过滤器工厂
作用:在请求中添加header信息(向目标服务)。对应过滤器工厂AddRequestHeaderGatewayFilterFactory
spring:
cloud:
gateway:
enabled: true
discovery:
locator:
enabled: true
lowerCaseServiceId: true
routes:
– id: AddRequestHeader_filter
uri: :20001
predicates:
– Path=/api/{user}
filters:
– AddRequestHeader=access-token,123456789
向目标服务:20001/api/xxx添加请求header access-token信息。
20001服务中有对应的接口:
@RestController
@RequestMapping("/api/")
public class UsersController {
@Resource
private HttpServletRequest request ;
@GetMapping("/{user}")
public Object save(@PathVariable("user") String username) {
System.out.println(username) ;
System.out.println("access-token = " + request.getHeader("access-token")) ;
return "success" ;
}
}
启动两个服务,测试: