是否可以将bean中的重复代码提取到单个方法中



我有这个云网关配置,我想提取并清理任何重复的代码。

@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("post_route", r -> r.path("/api/wallet/**")
.and().method("POST")
.and().readBody(BankRequestData.class, requestBody -> findWalletInstance(requestBody.externalReference()).equals("localhost:3000")).uri("http://localhost:3000"))
.route("post_route", r -> r.path("/api/wallet/**")
.and().method("POST")
.and().readBody(BankRequestData.class, requestBody -> findWalletInstance(requestBody.externalReference()).equals("localhost:3001")).uri("http://localhost:3001"))
.build();
}

这有可能吗?我不确定是否能做到。如有任何建议或建议,不胜感激。提前谢谢!

route()取一个Function<PredicateSpec,Route.AsyncBuilder>,因此需要一个返回该值的方法。

由于路由是相同的,除了host和post之外,您需要将其传递给方法。

private Function<PredicateSpec,Route.AsyncBuilder> walletRoute(String server) {
return r -> r.path("/api/wallet/**")
.and().method("POST")
.and().readBody(BankRequestData.class, requestBody ->
findWalletInstance(requestBody.externalReference()).equals(server))
.uri("http://" + server));
@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("post_route", walletRoute("localhost:3000"))
.route("post_route", walletRoute("localhost:3001"))
.build();
}

作为Andreas答案的变体,在Kotlin中,您也可以将函数定义为gatewayRoutes():中的局部函数

@Bean
fun RouteLocator gatewayRoutes(builder: RouteLocatorBuilder): routeLocator {
fun walletRoute(server: String) = { r: PredicateSpec ->
r.path("/api/wallet/**")
.and().method("POST")
.and().readBody(BankRequestData::class.java,
{ findWalletInstance(it.externalReference()) == server } )
.uri("http://$server")
}
return builder.routes()
.route("post_route", walletRoute("localhost:3000"))
.route("post_route", walletRoute("localhost:3001"))
.build()
}

或者作为初始化为匿名函数的局部变量:

@Bean
fun RouteLocator gatewayRoutes(builder: RouteLocatorBuilder): routeLocator {
val walletRoute = fun (server: String) = { r: PredicateSpec ->
r.path("/api/wallet/**")
.and().method("POST")
.and().readBody(BankRequestData::class.java,
{ findWalletInstance(it.externalReference()) == server } )
.uri("http://$server")
}
return builder.routes()
.route("post_route", walletRoute("localhost:3000"))
.route("post_route", walletRoute("localhost:3001"))
.build()
}

或者到lambda:

@Bean
fun RouteLocator gatewayRoutes(builder: RouteLocatorBuilder): routeLocator {
val walletRoute = { server: String -> { r: PredicateSpec ->
r.path("/api/wallet/**")
.and().method("POST")
.and().readBody(BankRequestData::class.java,
{ findWalletInstance(it.externalReference()) == server } )
.uri("http://$server")
}
}
return builder.routes()
.route("post_route", walletRoute("localhost:3000"))
.route("post_route", walletRoute("localhost:3001"))
.build()
}

所有这些选项都可以避免在包含类中添加成员,您可能会认为这更整洁——尽管这是否证明了更复杂的函数体的合理性可能取决于个人品味!

(注意:所有这些都是未经测试的,因为我没有相关的库,所以它可能有错误。请告诉我任何更正。希望它无论如何都能说明选项。(

最新更新