在单个位置(API 网关)聚合对微服务的调用。用户对 API 网关进行一次调用,然后 API 网关会调用每个相关的微服务。
程序示例
此实现展示了 API 网关模式对于电子商务网站的商品。该ApiGateway通过调用微服务ImageClientImpl和PriceClientImpl 返回图像和价格。客户可以在台式机上查看网站商品的价格信息和产品图像,因此ApiGateway调用微服务并聚合DesktopProduct模型中的数据。但是,移动用户只能看到价格信息;他们看不到产品图片。对于移动用户,ApiGateway唯一检索价格信息,它用于填充MobileProduct.
这是 Image 微服务实现。
public interface ImageClient {
String getImagePath();
}
// 发送到image模块,获取到图片数据
public class ImageClientImpl implements ImageClient {
@Override
public String getImagePath() {
var httpClient = HttpClient.newHttpClient();
var httpGet = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:50005/image-path"))
.build();
try {
var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
return httpResponse.body();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
这是 Price 微服务实现。
public interface PriceClient {
String getPrice();
}
// 发送到price模块,获取到图片价格数据
public class PriceClientImpl implements PriceClient {
@Override
public String getPrice() {
var httpClient = HttpClient.newHttpClient();
var httpGet = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:50006/price"))
.build();
try {
var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
return httpResponse.body();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
在这里我们可以看到 API Gateway 如何将请求映射到微服务。
public class ApiGateway {
@Resource
private ImageClient imageClient;
@Resource
private PriceClient priceClient;
/**
* 台式机 - 可以看到价格和图片
*/
@RequestMapping(path = "/desktop", method = RequestMethod.GET)
public DesktopProduct getProductDesktop() {
var desktopProduct = new DesktopProduct();
desktopProduct.setImagePath(imageClient.getImagePath());
desktopProduct.setPrice(priceClient.getPrice());
return desktopProduct;
}
/**
* 移动手机 - 只能看到价格
*/
@RequestMapping(path = "/mobile", method = RequestMethod.GET)
public MobileProduct getProductMobile() {
var mobileProduct = new MobileProduct();
mobileProduct.setPrice(priceClient.getPrice());
return mobileProduct;
}
}