我正在研究 Spring Cloud 并使用 Josh Long 的示例项目
有一个 API 网关预订客户端,它使用来自服务预订服务的数据,该服务提供 HATEOAS 响应,然后将其转换为简单的 JSON 响应。
@RestController
@RequestMapping("/reservations")
class ReservationApiGateway {
方法:
@HystrixCommand(fallbackMethod = "fallback")
@RequestMapping(method = RequestMethod.GET, value = "/names")
public Collection<String> names() {
return this.reservationReader
.read()
.getContent()
.stream()
.map(Reservation::getReservationName)
.collect(Collectors.toList());
}
我修改它以将 HATEOAS 响应转发给我。
@HystrixCommand(fallbackMethod = "fallback")
@RequestMapping(method = RequestMethod.GET, value = "/names")
public Resources<Resource<Reservation>> names() {
return this.reservationReader
.read();
}
这给了我一个 HATEAOS 响应,但链接全部来自预订服务- 。
"_links" : {
"self" : {
"href" : "**http://192.168.0.3:7000/reservations/1**"
},
"reservation" : {
"href" : "http://192.168.0.3:7000/reservations/1"
}
}
如何确保 Feign 更新到 API 网关的服务器和端口的链接?- http://192.168.0.3:9999/reservations/1
来自预订客户端的相同响应(与预订服务相同):
{
"_embedded" : {
"reservations" : [ {
"reservationName" : "Josh",
"_links" : {
"self" : {
"href" : "http://192.168.0.3:7000/reservations/1"
},
"reservation" : {
"href" : "http://192.168.0.3:7000/reservations/1"
}
}
}, {
"reservationName" : "Dr. Johnson",
"_links" : {
"self" : {
"href" : "http://192.168.0.3:7000/reservations/2"
},
"reservation" : {
"href" : "http://192.168.0.3:7000/reservations/2"
}
}
}, {
"reservationName" : "Dr. Syer",
"_links" : {
"self" : {
"href" : "http://192.168.0.3:7000/reservations/3"
},
"reservation" : {
"href" : "http://192.168.0.3:7000/reservations/3"
}
}
}, {
"reservationName" : "Dr. Pollack",
"_links" : {
"self" : {
"href" : "http://192.168.0.3:7000/reservations/4"
},
"reservation" : {
"href" : "http://192.168.0.3:7000/reservations/4"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://192.168.0.3:7000/reservations{?page,size,sort}",
"templated" : true
},
"profile" : {
"href" : "http://192.168.0.3:7000/profile/reservations"
},
"search" : {
"href" : "http://192.168.0.3:7000/reservations/search"
}
}
}
我想到了。
解决方案是在 X-Forwarded-Host http 标头中。X-Forwarded-Host 本质上告诉 Spring,任何具有此标头、链接中的主机和端口信息的 HATEOS 响应都应更新为 X-Forwarded-Host http 标头中提到的内容。
因此,在 API Gateway 预订客户端代码中,我添加了这个片段,它拦截了 Feign 对后端服务预订服务的调用,并将 http 标头添加到请求中。
@Component
class LanguageRequestInterceptor implements RequestInterceptor {
private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return;
}
HttpServletRequest request = requestAttributes.getRequest();
if (request == null) {
return;
}
requestTemplate.header(X_FORWARDED_HOST, "localhost:9999");
}
}
现在,所有 HATOES 响应都具有 API 网关的主机和端口信息,而不是后端 HATEOS 服务。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句