API Gateway模式 - 图1
    在单个位置(API 网关)聚合对微服务的调用。用户对 API 网关进行一次调用,然后 API 网关会调用每个相关的微服务。
    程序示例
    此实现展示了 API 网关模式对于电子商务网站的商品。该ApiGateway通过调用微服务ImageClientImpl和PriceClientImpl 返回图像和价格。客户可以在台式机上查看网站商品的价格信息和产品图像,因此ApiGateway调用微服务并聚合DesktopProduct模型中的数据。但是,移动用户只能看到价格信息;他们看不到产品图片。对于移动用户,ApiGateway唯一检索价格信息,它用于填充MobileProduct.
    这是 Image 微服务实现。

    1. public interface ImageClient {
    2. String getImagePath();
    3. }
    4. // 发送到image模块,获取到图片数据
    5. public class ImageClientImpl implements ImageClient {
    6. @Override
    7. public String getImagePath() {
    8. var httpClient = HttpClient.newHttpClient();
    9. var httpGet = HttpRequest.newBuilder()
    10. .GET()
    11. .uri(URI.create("http://localhost:50005/image-path"))
    12. .build();
    13. try {
    14. var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
    15. return httpResponse.body();
    16. } catch (IOException | InterruptedException e) {
    17. e.printStackTrace();
    18. }
    19. return null;
    20. }
    21. }

    这是 Price 微服务实现。

    1. public interface PriceClient {
    2. String getPrice();
    3. }
    4. // 发送到price模块,获取到图片价格数据
    5. public class PriceClientImpl implements PriceClient {
    6. @Override
    7. public String getPrice() {
    8. var httpClient = HttpClient.newHttpClient();
    9. var httpGet = HttpRequest.newBuilder()
    10. .GET()
    11. .uri(URI.create("http://localhost:50006/price"))
    12. .build();
    13. try {
    14. var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
    15. return httpResponse.body();
    16. } catch (IOException | InterruptedException e) {
    17. e.printStackTrace();
    18. }
    19. return null;
    20. }
    21. }

    在这里我们可以看到 API Gateway 如何将请求映射到微服务。

    1. public class ApiGateway {
    2. @Resource
    3. private ImageClient imageClient;
    4. @Resource
    5. private PriceClient priceClient;
    6. /**
    7. * 台式机 - 可以看到价格和图片
    8. */
    9. @RequestMapping(path = "/desktop", method = RequestMethod.GET)
    10. public DesktopProduct getProductDesktop() {
    11. var desktopProduct = new DesktopProduct();
    12. desktopProduct.setImagePath(imageClient.getImagePath());
    13. desktopProduct.setPrice(priceClient.getPrice());
    14. return desktopProduct;
    15. }
    16. /**
    17. * 移动手机 - 只能看到价格
    18. */
    19. @RequestMapping(path = "/mobile", method = RequestMethod.GET)
    20. public MobileProduct getProductMobile() {
    21. var mobileProduct = new MobileProduct();
    22. mobileProduct.setPrice(priceClient.getPrice());
    23. return mobileProduct;
    24. }
    25. }