我正在学习如何使用Spring Cloud构建API网关。我仔细阅读了文档中有关如何传递参数的内容,所有示例似乎都将它们显示为硬编码。但是,如果我有一个动态值怎么办?
例如,我有这种类型的请求:http://localhost:8080/people/lookup?searchKey=jdoe,
如何传递“ jdoe”部分?
我尝试了以下代码,并且仅当我在代码中对值进行硬编码时,它才有效。即.filters(f -> f.addRequestParameter("searchKey", "jdoe")
。该测试还证明了我的发现服务器(Eureka)正常工作。
我不确定如何使用提供的构建器方法访问值。这是一个简单的场景,但是我很惊讶地发现那里没有太多的示例或文档,所以肯定是我自己。
@SpringBootApplication
@EnableEurekaClient
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("people-service", r -> r.path("/people/active-associates")
.uri("lb://people-service"))
.route(r -> r.path("/people/lookup")
.filters(f -> f.addRequestParameter("searchKey", howDoIPassDynamicValueHere))
.uri("lb://people-service")
.id("addrequestparameter_route"))
.build();
}
当我直接调用该服务时,这显然是有效的,因为我的微服务控制器使用@RequestParam来像这样处理它……非常简单:
@RestController
@RequestMapping(value = "/people")
public class PersonController {
@Autowired
private PersonService personService;
/**
* Searches by FirstName, Lastname or NetworkId.
*
* @param searchKey
* @return ResponseEntity<List<Person>>
*/
@GetMapping(value = "/lookup")
public ResponseEntity<List<Person>> findPersonsBySearchKey(@RequestParam(name = "searchKey") String searchKey) {
List<Person> people = personService.findActivePersonsByFirstLastNetworkId(searchKey.trim().toLowerCase());
return new ResponseEntity<List<Person>>(people, HttpStatus.OK);
}
}
感谢评论,这对我来说很有意义。当我阅读有关过滤器的addRequestParameter()方法的文档时,我想我确实想过。我认为如果我的请求有参数,则需要使用该方法。 ing了一天,我简直不敢这么简单。因此,我通过删除该过滤器来使它起作用:
@SpringBootApplication
@EnableEurekaClient
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("people-service", r -> r.path("/people/active-associates")
.uri("lb://people-service"))
.route(r -> r.path("/people/lookup")
.uri("lb://people-service"))
.build();
}
}