Microservice Architecture 简明教程

Microservice Architecture - Quick Guide

Microservice Architecture - Introduction

微服务是一种基于服务的应用程序开发方法。此方法中,大型应用程序将被划分为最小的独立服务单元。微服务是通过将整个应用程序划分为一系列相互关联的服务来实现面向服务架构(SOA)的过程,其中每个服务只满足一项业务需求。

Microservice is a service-based application development methodology. In this methodology, big applications will be divided into smallest independent service units. Microservice is the process of implementing Service-oriented Architecture (SOA) by dividing the entire application as a collection of interconnected services, where each service will serve only one business need.

The Concept of Going Micro

在面向服务架构中,整个软件包将被细分为小的、相互关联的业务单元。每个这些小的业务单元将使用不同的协议互相通信,以向客户交付成功的业务。现在的问题是,微服务架构(MSA)与 SOA 有什么不同?一句话来说,SOA 是一种设计模式,微服务是实现 SOA 的实现方法,或者我们可以说微服务是 SOA 的一种类型。

In a service-oriented architecture, entire software packages will be sub-divided into small, interconnected business units. Each of these small business units will communicate to each other using different protocols to deliver successful business to the client. Now the question is, how Microservice Architecture (MSA) differs from SOA? In one word, SOA is a designing pattern and Microservice is an implementation methodology to implement SOA or we can say Microservice is a type of SOA.

以下是开发以微服务为导向的应用程序时需要记住的一些规则。

Following are some rules that we need to keep in mind while developing a Microservice-oriented application.

  1. Independent − Each microservice should be independently deployable.

  2. Coupling − All microservices should be loosely coupled with one another such that changes in one will not affect the other.

  3. Business Goal − Each service unit of the entire application should be the smallest and capable of delivering one specific business goal.

让我们考虑一个在线购物门户的例子,以深入了解微服务。现在让我们将整个电子商务门户分解为小型业务单元,例如用户管理、订单管理、入住、支付管理、配送管理等。一笔成功的订单需要在特定时间范围内历经所有这些模块。以下是与电子商务系统相关的不同业务单元的合并图像。

Let us consider an example of online shopping portal to understand microservice in depth. Now, let us break this entire E-commerce portal into small business units such as user management, order management, check-in, payment management, delivery management, etc. One successful order needs to proceed through all of these modules within a specific time frame. Following is the consolidated image of different business units associated with one electronic commerce system.

electronic commerce solutions

这些业务模块中的每一个都应该有自己的业务逻辑和利益相关者。它们与其他第三方供应商软件进行通信以满足某些特定需求,并且彼此之间也进行通信。例如,订单管理可能会与用户管理进行通信以获取用户信息。

Each of these business modules should have its own business logic and stakeholders. They communicate with other third party vendor softwares for some specific needs, and also with each other. For example, order management may communicate with user management to get user information.

现在,考虑到您正在运行包含前面提到的所有业务单元的在线购物门户,您确实需要一个由前端、后端、数据库等不同层组成的企业级应用程序。如果您的应用程序没有进行扩展并在一个单独的 war 文件中得到完全开发,那么它将被称为典型的单体应用程序。据 IBM 所述,典型的单体应用程序在内部应具有以下模块结构,其中只有一个端点或应用程序负责处理所有用户请求。

Now, considering you are running an online shopping portal with all of these business units mentioned earlier, you do need some enterprise level application consisting of different layers such as front-end, back-end, database, etc. If your application is not scaled and completely developed in one single war file, then it will be called as a typical monolithic application. According to IBM, a typical monolithic application should possess the following module structure internally where only one endpoint or application will be responsible to handle all user requests.

database

在上面的图像中,您可以看到用于存储不同用户和业务数据的不同模块,例如数据库。在前端,我们有不同的设备,我们通常在那里呈现用户或业务数据以供使用。在中间,我们有一个包可以是可部署的 EAR 或 WAR 文件,它接受用户末端的请求,借助于资源对其进行处理,然后将其呈现在用户面前。在业务需要对上述范例进行任何更改之前,一切都很好。

In the above image, you can see different modules such as Database for storing different users and business data. At the front-end, we have different device where we usually render user or business data to use. In the middle, we have one package that can be a deployable EAR or WAR file that accepts request form the users end, processes it with the help of the resources, and renders it back to the users. Everything will be fine until business wants any changes in the above example.

考虑以下情况,您必须根据业务需求更改应用程序。

Consider the following scenarios where you have to change your application according to the business needs.

业务单元需要对“搜索”模块进行一些更改。然后,您需要更改整个搜索过程并重新部署应用程序。在这种情况下,您正在重新部署其他单元而根本没有进行任何更改。

Business unit needs some changes in the “Search” module. Then, you need to change the entire search process and redeploy your application. In that case, you are redeploying your other units without any changes at all.

business unit

现在,您的业务部门需要对“签出”模块进行一些更改以包括“钱包”选项。您现在必须更改“签出”模块并将它重新部署到服务器中。请注意,您正在重新部署软件包的不同模块,而我们并没有对其进行任何更改。这就是面向服务的架构,更具体地说是微服务架构的概念的由来。我们可以以这种方式开发单体应用程序,使得软件的每个模块都充当独立的单元,能够独立地处理单个业务任务。

Now again your business unit needs some changes in “Check out” module to include “wallet” option. You now have to change your “Check out” module and redeploy the same into the server. Note, you are redeploying the different modules of your software packages, whereas we have not made any changes to it. Here comes the concept of service-oriented architecture more specific to Microservice architecture. We can develop our monolithic application in such a manner that each and every module of the software will behave as an independent unit, capable of handling a single business task independently.

考虑以下示例。

Consider the following example.

在上述架构中,我们不会创建包含端到端紧凑服务的任何 ear 文件。相反,我们通过将它们作为服务公开来划分软件的不同部分。软件的任何部分都可以通过使用各自的服务来轻松地彼此进行通信。这就是微服务在现代 Web 应用程序中扮演重要角色的方式。

In the above architecture, we are not creating any ear file with compact end-to-end service. Instead, we are dividing different parts of the software by exposing them as a service. Any part of the software can easily communicate with each other by consuming respective services. That’s how microservice plays a great role in modern web application.

让我们在微服务的意义上比较我们的购物车示例。我们可以将购物车分解为不同的模块,例如“搜索”、“筛选”、“签出”、“购物车”、“推荐”等。如果我们想构建一个购物车门户,那么我们必须构建上述模块,使其能够彼此连接,以提供 24x7 良好的购物体验。

Let us compare our shopping cart example in the line of microservice. We can break down our shopping cart in the different modules such as “Search”, ”Filter”, “Checkout”, “Cart”, “Recommendation”, etc. If we want to build a shopping cart portal then we have to build the above-mentioned modules in such a manner that they can connect to each other to give you a 24x7 good shopping experience.

Advantages & Disadvantages

以下是一些使用微服务而非使用单体应用程序的优势:

Following are some points on the advantages of using microservice instead of using a monolithic application.

Advantages

  1. Small in size − Microservices is an implementation of SOA design pattern. It is recommended to keep your service as much as you can. Basically, a service should not perform more than one business task, hence it will be obviously small in size and easy to maintain than any other monolithic application.

  2. Focused − As mentioned earlier, each microservice is designed to deliver only one business task. While designing a microservice, the architect should be concerned about the focal point of the service, which is its deliverable. By definition, one microservice should be full stack in nature and should be committed to delivering only one business property.

  3. Autonomous − Each microservice should be an autonomous business unit of the entire application. Hence, the application becomes more loosely coupled, which helps to reduce the maintenance cost.

  4. Technology heterogeneity − Microservice supports different technologies to communicate with each other in one business unit, which helps the developers to use the correct technology at the correct place. By implementing a heterogeneous system, one can obtain maximum security, speed and a scalable system.

  5. Resilience − Resilience is a property of isolating a software unit. Microservice follows high level of resilience in building methodology, hence whenever one unit fails it does not impact the entire business. Resilience is another property which implements highly scalable and less coupled system.

  6. Ease of deployment − As the entire application is sub-divided into small piece of units, every component should be full stack in nature. All of them can be deployed in any environment very easily with less time complexity unlike other monolithic applications of the same kind.

以下是有关微服务架构缺点的一些要点。

Following are some points on the disadvantages of microservice architecture.

Disadvantages

  1. Distributed system − Due to technical heterogeneity, different technologies will be used to develop different parts of a microservice. A huge set of skilled professionals are required to support this big heterogeneous distributed software. Hence, distributed and heterogeneity stands as a number one disadvantage of using microservice.

  2. Cost − Microservice is costly, as you have to maintain different server space for different business tasks.

  3. Enterprise readiness − Microservice architecture can be considered as a conglomerate of different technologies, as technology is evolving day-by-day. Hence, it is quite difficult to make a microservice application enterprise ready to compare to conventional software development model.

Microservice Over SOA

下表列出了 SOA 和微服务的某些特性,展示了与 SOA 相比使用微服务的重要性。

The following table lists certain features of SOA and Microservice, bringing out the importance of using microservice over SOA.

Component

SOA

Microservice

Design pattern

SOA is a design paradigm for computer software, where software components are exposed to the outer world for usage in the form of services.

Micro Service is a part of SOA. It is a specialized implementation of SOA.

Dependency

Business units are dependent on each other.

All business units are independent of each other.

Size

Software size is bigger than the conventional software.

Software size is small.

Technology

Technology stack is less than Microservice.

Microservice is heterogeneous in nature as exact technologies are used to perform a specific task. Microservices can be considered as a conglomerate of many technologies.

Autonomous and Focus

SOA applications are built to perform multiple business tasks.

Microservice applications are built to perform a single business task.

Nature

Monolithic in nature.

Full stack in nature.

Deployment

Deployment is time-consuming.

Deployment is very easy. Hence, it will be less time-consuming.

Cost-effectiveness

More cost-effective.

Less cost-effective.

Scalability

Less compared to Microservices.

Fully scaled.

Example

Let us consider one online CAB booking application. If we want to build that application using SOA, then its software units will be − GetPayments And DriverInformation And MappingDataAPIAuthenticateUsersAnd DriversAPI

If the same application is built using microservice architecture, then its APIs will be − SubmitPaymentsServiceGetDriverInfoServiceGetMappingDataServiceAuthenticateUserServiceAuthenticateDriverService

Microservice Architecture - Scaling

伸缩是将软件分解为不同单元的过程。伸缩还从可伸缩性的角度进行定义。可伸缩性是实现应用程序更多高级功能的潜力。它有助于提高应用程序的安全性、持久性和可维护性。我们在行业中采用了三种类型的伸缩程序。以下是不同的伸缩方法以及相应的真实示例。

Scaling is a process of breaking down a software in different units. Scaling also defines in terms of scalability. Scalability is the potential to implement more advance features of the application. It helps to improve security, durability, and maintainability of the application. We have three types of scaling procedures that is followed in the industries. Following are the different scaling methodologies along with the corresponding real-life examples.

X-Axis Scaling

X 轴伸缩也称为水平伸缩。在此过程中,整个应用程序被细分为不同的水平部分。通常,任何 Web 服务器应用程序都可以进行这种类型的伸缩。考虑一个遵循水平伸缩的普通 MVC 架构,如下图所示。

X-axis scaling is also called as horizontal scaling. In this procedure, the entire application is sub-divided into different horizontal parts. Normally, any web server application can have this type of scaling. Consider a normal MVC architecture that follows horizontal scaling as shown in the following figure.

x axis scaling

例如,我们可以考虑任何 JSP servlet 应用程序。在此应用程序中,控制器控制每个请求,并且它会在必要时与模型通信以生成视图。通常,单体应用程序遵循这种伸缩方法。X 轴伸缩本质上非常基本,并且非常省时。在此方法中,将根据单元负责的不同任务对一款软件进行伸缩。例如,控制器负责控制传入和传出的请求,视图负责向浏览器中的用户表示业务功能,而模型负责存储我们的数据并充当数据库。

As an example, we can consider any JSP servlet application. In this application, the controller controls every request and it will generate view by communicating with the model whenever necessary. Normally, monolithic applications follow this scaling method. X-Axis scaling is very basic in nature and it is very less time consuming. In this methodology, one software will be scaled depending on its different task that the unit is responsible for. For example, the controller is responsible for controlling the incoming and outgoing request, the view is responsible for representing the business functionality to the users in the browser, while the model is responsible to store our data and it works as the database.

Y-Axis Scaling

Y 轴伸缩也称为垂直伸缩,包括任何资源级伸缩。任何 DBaaS 或 Hadoop 系统都可以被认为是 Y 轴伸缩。在此类型的伸缩中,用户请求被重定向并受到限制,方法是实现一些逻辑。

Y-axis scaling is also called as a vertical scaling that includes any resource level scaling. Any DBaaS or Hadoop system can be considered to be Y-axis scaled. In this type of scaling, the users request is redirected and restricted by implementing some logic.

让我们以 Facebook 为例。Facebook 每秒需要处理 179 万用户;因此,控制流量是 Facebook 网络工程师的巨大责任。为了克服任何危险,他们遵循 Y 轴伸缩,其中包括同时运行具有相同应用程序的多个服务器。现在,为了控制这种巨大的流量,Facebook 将所有流量从一个区域重定向到特定服务器,如下图所示。基于区域的这种流量传输在架构语言中称为负载平衡。

Let us consider Facebook as an example. Facebook needs to handle 1.79 million users in every second; hence, controlling the traffic is a huge responsibility of Facebook network engineers. To overcome from any hazard, they follow Y-axis scaling which includes running multiple servers with the same application at the same time. Now in order to control this huge level of traffic, Facebook redirects all the traffic from one region to a specific server, as depicted in the image. This transferring of traffic based on the region is called load balancing in architectural language.

y axis scaling

将资源分解为小型独立业务单元的这种方法称为 Y 轴伸缩。

This method of breaking down resources into small independent business units is known as Y-Axis scaling.

Z-Axis Scaling

X 轴和 Y 轴伸缩很容易理解。然而,一个应用程序也可以在业务级别进行缩放,这称为 Z 轴缩放。以下是将出租车服务应用程序扩展到不同垂直业务单元中的示例。

X- and Y-axis scaling is pretty much easier to understand. However, one application can also be scaled at the business level, which is called as Z-axis scaling. Following is an example of scaling a cab service application in the different verticals of business units.

driver management

Advantages of Scaling

  1. Cost − Proper scaling of a software will reduce the cost for maintenance.

  2. Performance − Due to loose coupling, the performance of a properly scaled software is always better than a non-scaled software.

  3. Load distribution − Using different technologies, we can easily maintain our server load.

  4. Reuse − Scalability of a software also increases the usability of the software.

Microservice Architecture - Blueprint

微服务在内部实现 SOA。从更广泛的意义上讲,我们可以将其视为一个 SOA 应用程序的子集。

Microservice implements SOA internally. In a broader sense, we can consider it as a subset of one SOA application.

Rule & Workflow

以下是在开发微服务时需要遵循的原则。

Following are the principles that need to be taken care of while developing a microservice.

  1. High Cohesion − All the business models need to be sub-divided into the smallest business part as much as possible. Each service should be focused to perform only one business task.

  2. Independent − All the services should be full stack in nature and independent of each other.

  3. Business Domain Centric − Software will modularize according to the business unit and is not tier based.

  4. Automation − Testing deployment will be automated. Try to introduce minimal human interaction.

  5. Observable − Each service will be full stack in nature and they should be independently deployable and observable like an enterprise application.

Team Management

“两披萨规则”是一种限制微服务开发团队内参加者数量的规则。根据此规则,一个应用程序的团队成员数量应尽可能少,以至于两份披萨就能满足他们的需求。一般来说,该数量不应超过 8。由于微服务本质上是全栈的,因此团队也是全栈的。为了提高效率,我们需要建立一个由不超过 8 名拥有该服务所需所有专业知识的成员组成的团队。

“Two Pizza Rule” is a kind of rule that restricts the number of attendees in a microservice development team. According to this rule, number of the team members of one application should be so small such that they can be fed by two pizza. Generally, the number should not be more than 8. As microservice is full stack in nature, the team is also full stack in nature. To increase the productivity, we need to build one team of maximum 8 members with all kinds of expertise required for that service.

Task Management

任务在软件开发生命周期中扮演着重要角色。将大型应用开发分解为若干个小任务单元。假设我们需要开发一款如 Facebook 这样的应用程序,那么“登录”功能可视为整个构建过程中的一个任务。在高技能专业人员的监控下,需要适当地监控这些任务的进度。敏捷是业界遵循的知名流程结构,用于满足良好的任务管理。

Task is an important role in software development life cycle. Developing a large scale application can be broken down into several small units of task. Let us consider we need to develop one application such as Facebook. Then, “Log in” functionality can be considered as a task of the entire build process. Progress for each of these tasks need to be monitored properly under highly skilled professionals. Agile is the well-known process structure followed in the industries to keep up with good task management.

Different Elements

到目前为止,我们已经了解了什么是微服务以及它在现代 MVC 架构之上有哪些基本需求。在本章中,我们将学习此架构的不同元素,这些元素对于服务同等重要。

Till now we have learned what is Microservice and what are the basic needs of it above the modern MVC architecture. In this chapter, we will learn the different elements of this architecture that are equally important for a service.

Categories of Services

按微服务命名,我们假设它将是可以通过 HTTP 协议使用的服务,然而我们需要了解可以使用此架构构建哪种服务。以下是可以使用微服务架构实现的服务列表。

By the name Microservice, we assume that it will be a service that can be consumed over HTTP protocols, however we need to know what kind of services can be build using this architecture. Following is the list of services that can be implemented using Microservice architecture.

Platform as a Service [PaaS] - 在这种面向服务架构中,平台被赋予一种可以根据业务需求进行定制的工具。PaaS 在移动应用程序开发中发挥着重要作用。PaaS 最好的例子是 Google App Engine,其中 Google 提供了不同的有用平台来构建你的应用程序。PaaS 最初开发是为了向开发人员提供内置架构或基础设施。它在大大减少的时间内降低了更高级别的编程复杂性。以下是 Google 提供的 PaaS 的快照。

Platform as a Service [PaaS] − In this service-oriented architecture, the platform is given as a tool which can be customized according to the business needs. PaaS plays an important role in mobile application development. The greatest example of PaaS is Google App engine, where Google provides different useful platform to build your application. PaaS originally develops to provide a built-in architecture or infrastructure to developers. It reduces the higher level programming complexity in dramatically reduced time. Following is a snapshot of Google provided PaaS.

google cloud platform

Software as a Service [SaaS] - 软件即服务是一种软件许可业务,其中软件集中托管并按订阅方式授权。SaaS 主要可以通过浏览器访问,并且是许多业务垂直领域中非常常见的架构模式,例如人力资源管理 (HRM)、企业资源规划 (ERP)、客户关系管理 (CRM) 等。以下屏幕快照显示了 Oracle 提供的不同 SaaS 的示例。

Software as a Service [SaaS] − Software as a Service is a software licensing business, where the software is centrally hosted and licensed on a subscription basis. SaaS can be accessed mainly through the browser and it is a very common architecture pattern in many business verticals such as Human Resource Management (HRM), Enterprise Resource Planning (ERP), Customer Relationship Management (CRM), etc. Following screenshot shows examples of different SaaS provided by Oracle.

common infrastructure services

Infrastructure as a Service [IaaS] - 基础设施在 IT 行业中扮演着重要的角色。使用云计算,一些组织提供虚拟基础设施作为服务。IaaS 对于在软件开发中带来敏捷性、成本效益、安全性、性能和生产力非常有帮助。Amazon EC2 和 Microsoft Azure 是 IaaS 最重要的例子。下图描述了 AWS 的一个例子,其中数据中心被提供为 IaaS。

Infrastructure as a Service [IaaS] − Infrastructure plays a good role in IT industries. Using cloud computing, some of the organizations provide virtual infrastructure as their services. IaaS is very helpful for bringing agility, cost-effectiveness, security, performance, productivity, etc. in software development. Amazon EC2 and Microsoft Azure are the biggest examples of IaaS. The following image depicts an example of AWS, where the data center is provided as IaaS.

data center services

Data as a Service [DaaS] - 信息技术处理数据,一些顶级行业领导者认为数据将成为社会的新的支撑。DaaS 是这样的一种服务,其中数据与商业集团共享用于研究和分析。DaaS 在数据访问层带来了简单性、敏捷性和安全性。以下是 Oracle Data Cloud 的一个例子,可以根据你自己的业务需求访问或获得许可。

Data as a Service [DaaS] − Information technology deals with data and some of the top industry leaders believe that data will be the new sustenance of the society. DaaS is a type of service where data is shared with business conglomerates for research and analysis. DaaS brings simplicity, agility, and security in the data access layer. Following is an example of Oracle Data cloud, which can be accessed or licensed for your own business needs.

oracle data cloud

Back End as a Service [BaaS] - BaaS 也称为 MBaaS,表示移动后端即服务。在这种类型的服务中,应用程序的后端将提供给业务部门以供其自己的业务投资。所有推送通知、社交网络服务都属于这种类型的服务。Facebook 和 Twitter 是著名的 BaaS 服务提供商的例子。

Back End as a Service [BaaS] − BaaS is also known as MBaaS, which means mobile back-end as a service. In this type of service, backend of the application will be provided to business units for their own business ventures. All push notifications, social networking services fall under this type of services. Facebook and Twitter are examples of well-known BaaS service provider.

Security

在处理大量客户数据时,安全性发挥着重要作用。安全问题与市场上所有类型的服务相关。无论你使用哪种云 - 私有、公有、混合等,都应在各个层面维护安全性。整个安全问题可以大致细分为以下部分:

When it comes to dealing with tons of customer data, security plays an important role. Security issue is associated with all kinds of services available in the market. Whatever the cloud you are using - private, public, hybrid, etc., security should be maintained at all levels. Entire security issue can be broadly sub-divided into the following parts −

  1. Security issue faced by service providers − This type of security issue is faced by the service providers such as Google, Amazon, etc. To ensure security protection, background check of the client is necessary especially of those who have direct access to the core part of the cloud.

  2. Security issue faced by consumers − Cloud is cost friendly, hence it is widely used across industries. Some organizations store the user details in third party data centers, and pull the data whenever required. Hence, it is mandatory to maintain security levels such that any private data of one customer should not be visible to any other users.

为了防止上述安全问题,以下是组织使用的一些防御机制。

To prevent the above-mentioned security problems, following are some of the defensive mechanisms used by organizations.

  1. Deterrent Control − Know you potential threat to reduce cyber-attack.

  2. Preventive Control − Maintain high level authentication policy to access your cloud.

  3. Detective Control − Monitor your users and detect any potential risk.

  4. Corrective Control − Work closely with different teams and fix the issues that arise during the detective control phase.

Composition Patterns

软件组合是指构建软件产品的方法。它基本上涉及高级软件架构图,其中软件的不同模块将针对特定业务目标进行通信。在本章中,我们将了解组织中广泛使用的不同软件组合模式。在微服务中,我们将每个功能拆分为一个进程。这些服务中的每一个都将具有独立性和全栈特性。

Software composition means the way to build your software product. Basically it deals with high level software architecture diagram where different modules of your software will communicate for specific business goals. In this chapter, we will learn about different software composition patterns widely used in organizations. In microservice, we split each function into one process. Each of these services will be independent and full stack in nature.

功能分解在构建微服务中发挥着重要作用。它为您的应用程序提供了敏捷性、灵活性和可伸缩性。

Functional decomposition plays an important role in building your microservices. It provides agility, flexibility, and scalability to your application.

Aggregator Pattern

聚合器模式是最简单的 Web 模式,可以在开发微服务时实现。在此组合模式中,一个简单的 Web 模块将充当负载平衡器,这意味着它将根据要求调用不同的服务。以下是描绘具有聚合器设计的简单微服务 Web 应用程序的图表。如下面的图像所示,“聚合器”负责逐个调用不同的服务。如果我们需要对服务 A、B 和 C 的结果应用任何业务逻辑,那么我们可以在聚合器本身中实现业务逻辑。

Aggregator pattern is the simplest web pattern that can be implemented while developing a microservice. In this composition pattern, a simple web module will act as a load balancer, which means it will call different services as per requirements. Following is a diagram depicting a simple microservice web app with aggregator design. As seen in the following image, the "Aggregator" is responsible for calling different services one by one. If we need to apply any business logic over the results of the service A, B and C, then we can implement the business logic in the aggregator itself.

aggregator pattern

聚合器可以再次对外界公开为另一项服务,其他人可以在需要时使用它。在开发聚合器模式 Web 服务时,我们需要记住,我们的每个服务 A、B 和 C 都应该有自己的缓存层,并且它本质上应该是全栈的。

An aggregator can be again exposed as another service to the outer world, which can be consumed by others whenever required. While developing aggregator pattern web service, we need to keep in mind that each of our services A, B and C should have its own caching layers and it should be full stack in nature.

Proxy Pattern

代理微服务模式是聚合器模型的一个变体。在这个模型中,我们将使用代理模块来代替聚合模块。代理服务可以单独调用不同的服务。

Proxy microservice pattern is a variation of the aggregator model. In this model we will use proxy module instead of the aggregation module. Proxy service may call different services individually.

proxy pattern

在代理模式中,我们可以通过提供一个转储代理层来构建一级的额外安全。该层的作用类似于接口。

In Proxy pattern, we can build one level of extra security by providing a dump proxy layer. This layer acts similar to the interface.

Chained Pattern

顾名思义,此类型的组合模式将遵循链式结构。在这里,我们不会在客户端和服务层之间使用任何内容。相反,我们将允许客户端直接与服务进行通信,并且所有服务将以这样的方式链接在一起,即一个服务的输出将成为下一个服务的输入。下图显示了一个典型的链式模式微服务。

As the name suggests, this type of composition pattern will follow the chain structure. Here, we will not be using anything in between the client and service layer. Instead, we will allow the client to communicate directly with the services and all the services will be chained up in a such a manner that the output of one service will be the input of the next service. Following image shows a typical chained pattern microservice.

chained pattern

这种架构的一个主要缺点是,客户端将在整个过程完成前被阻止。因此,强烈建议将链条的长度尽可能短。

One major drawback of this architecture is, the client will be blocked until the entire process is complete. Thus, it is highly recommendable to keep the length of the chain as short as possible.

Branch Microservice Pattern

分支微服务是聚合器模式和链模式的扩展版本。在此设计模式中,客户端可以直接与服务通信。此外,一个服务可以同时与多个服务通信。以下是分支微服务的图表表示。

Branch microservice is the extended version of aggregator pattern and chain pattern. In this design pattern, the client can directly communicate with the service. Also, one service can communicate with more than one services at a time. Following is the diagrammatic representation of Branch Microservice.

branch microservice pattern

分支微服务模式允许开发人员动态配置服务调用。所有服务调用都将以并发方式发生,这意味着服务 A 可以同时调用服务 B 和 C。

Branch microservice pattern allows the developer to configure service calls dynamically. All service calls will happen in a concurrent manner, which means service A can call Service B and C simultaneously.

Shared Resource Pattern

共享资源模式实际上是前面提到的所有类型模式的集合。在此模式中,客户端或负载平衡器将根据需要直接与每个服务进行通信。这是大多数组织广泛遵循的最有效的设计模式。以下是共享资源设计模式的图表表示。

Shared resource pattern is actually a conglomerate of all types of patterns mentioned earlier. In this pattern, the client or the load balancer will directly communicate with each service whenever necessary. This is the most effective designing pattern followed widely in most organizations. Following is a diagrammatic representation of the Shared Resource design pattern.

shared resource pattern

Microservice Architecture - Hands-On SOA

在本章中,我们将开发基于 CRUD 的具有 SOA 架构的应用程序。稍后在后续章节中,我们将把该服务分解成微服务,并且我们将学习 SOA 和微服务架构之间的基本区别。

In this chapter, we will develop a CRUD-based application with SOA architecture. Later on in the subsequent chapters, we will break this service into microservice and we will learn the basic difference between SOA and microservice architecture.

System Configuration and Setup

在本节中,我们将构建一个示例 CRUD 应用程序,无论何时调用我们的服务都会返回 JSON 对象作为响应。我们将使用 Jersey 框架来开发它。以下是设置本地系统环境的步骤。

In this section, we will build a sample CRUD application, which will return a JSON object as a response whenever we call our service. We will use the Jersey framework to develop the same. Following are the steps to set up your local system environment.

Developing a CRUD Application

Step 1 − 我们将使用 NetBeans 作为开发 IDE。请下载并安装 NetBeans 官方网站 https://netbeans.org/downloads/ 上可用的最新版本。

Step 1 − We will use NetBeans as development IDE. Please download and install the latest version available on NetBeans official website https://netbeans.org/downloads/.

Step 2 − 打开您的 NetBeans IDE。转到“文件 → 新建项目”。将弹出以下屏幕截图。选择“Maven”作为类别,选择“Project from ArchType”作为项目,然后点击下一步。

Step 2 − Open your NetBeans IDE. Go to “File → New Project”. The following screenshot pops up. Choose “Maven” as a category and select “Project from ArchType” as a project and hit Next.

screenshot pops up

这将下载创建您的第一个 Maven 项目和 RESTful Web Service 所需的所有 jar 文件。

This will download all the required jar files to create your first ever Maven project and RESTful Web Service.

Step 3 − 点击上一步中的下一步按钮,将出现以下屏幕截图。在这里,您必须指定 Maven Archetype。

Step 3 − On hitting the Next button in the previous step, the following screenshot appears. Here, you will have to specify the Maven Archetype.

maven archetype

在搜索框中,搜索“Jersey-archType-Webapp(2.16)”并勾选“显示旧版本”复选框。

In the search box, search for “Jersey-archType-Webapp(2.16)” and check the “Show Older” checkbox.

Step 4 − 选择它之后,您将被重定向到以下屏幕。从列表中选择首选的 jar,然后点击下一步继续。

Step 4 − Once you have selected the same, you will be redirected to the following screen. Select the preferred jar from the list and hit Next to continue.

redirected screen

Step 5 − 在此步骤中,您需要提供项目的名称及其 Group Id 以及包详细信息。在提供所有这些信息后,点击完成以继续。

Step 5 − In this step, you need to provide the name of your project and its Group Id as well as the package details. After providing all this information, hit Finish to continue.

group Id

Step 6 − 您的工作区设置已完成。项目目录将如下所示。

Step 6 − You are done with your workspace setup. The project directory will look like the following.

workspace setup

查看您的“Dependencies”文件夹,您会发现 Maven 已为该项目自动下载了所有必需的 jar 文件。

Check out your “Dependencies” folder and you will find that Maven has automatically downloaded all the required jar files for this project.

dependencies

Step 7 − 您的工作区已完成设置,您可以开始编写代码。继续创建四个类和包,如下面的屏幕截图所示。您会发现 Maven 已经创建了 MyResource.java,因为 Maven 足够聪明,可以检测到您将要构建自己的 Web 服务。

Step 7 − Your workspace is set up and you can start with coding. Go ahead and create four classes and packages as mentioned in the following screenshot. You can find MyResource.java is already created by Maven, as Maven is smart enough to detect that you are going to build your own web service.

source packages

Step 8 − 完成上述步骤后,我们将构建我们的 POJO 类 UserProfile.java,如下所示。

Step 8 − Once done with the above step, we will construct our POJO class that is UserProfile.java as follows.

package com.tutorialspoint.userprofile.Model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class UserProfile {
   private long ProId;
   private String FName;
   private String LName;
   private String Add;
   public UserProfile(){}

   public UserProfile(long Proid, String Fname, String Lname,String Add) {
      this.ProId = Proid;
      this.FName = Fname;
      this.LName = Lname;
      this.Add = Add;
   }
   public long getProId() {
      return ProId;
   }
   public void setProId(long ProId) {
      this.ProId = ProId;
   }
   public String getFName() {
      return FName;
   }
   public void setFName(String FName) {
      this.FName = FName;
   }
   public String getLName() {
      return LName;
   }
   public void setLName(String LName) {
      this.LName = LName;
   }
   public String getAdd() {
      return Add;
   }
   public void setAdd(String Add) {
      this.Add = Add;
   }
}

Step 9 − 现在,我们将创建我们的数据库类。由于这是学习材料的一部分,我们将不使用任何 DB 作为我们的数据库。我们将使用内置的 Java 内存作为我们的临时内存。如您在以下代码集中所见,我们将使用 MAP 作为我们的数据库。我们将对执行的所有 Web 服务操作在此类中定义的 MAP 上进行操作。

Step 9 − Now we will create our Database class. As this is a part of learning material, we will not use any DB as our database. We will use an inbuilt Java memory to work as our temporary memory. As you can see in the following set of code, we will use MAP as our database. All the web service operation that we perform, we will work on this MAP defined in the class.

package com.tutorialspoint.userprofile.DAO;

import com.tutorialspoint.userprofile.Model.UserProfile;

import java.util.HashMap;
import java.util.Map;

public class DatabaseClass {
   private static Map<Long,UserProfile> messages = new HashMap<Long,UserProfile>();
   public static Map<Long,UserProfile> getUsers() {
      return messages;
      // Each time this method will return entire map as an instance of database
   }
}

Step 10 − 现在让我们构建我们的服务类。继续将以下代码集复制并粘贴到“ProfileService.java”类中。这是我们声明所有向外部公开的 Web 服务方法的类。我们需要创建一个 DatabaseClass 的引用,以便可以在此类中访问我们的临时数据库。

Step 10 − Now let us build our service class. Go ahead and copy paste the following set of code in the “ProfileService.java” class. This is the class where we will declare all our web service methods that is to be exposed for the outer world. We need to create one reference of our DatabaseClass such that our temporary database can be accessed in this class.

package com.tutorialspoint.userprofile.service;

import com.tutorialspoint.userprofile.DAO.DatabaseClass;
import com.tutorialspoint.userprofile.Model.UserProfile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ProfileService {
   private Map<Long,UserProfile> Userprofiles = DatabaseClass.getUsers();

   // Creating some predefine profile and populating the same in the map
   public ProfileService() {
      UserProfile m1 = new UserProfile(1L,"Tutorials1","Point1","TutorialsPoint.com");
      UserProfile m2 = new UserProfile(2L,"Tutorials2","Point2","TutorialsPoint.com2");
      UserProfile m3 = new UserProfile(3L,"Tutorials3","Point3","TutorialsPoint.com3");
      UserProfile m4 = new UserProfile(4L,"Tutorials4","Point4","TutorialsPoint.com4");

      Userprofiles.put(1L, m1);
      Userprofiles.put(2L, m2);
      Userprofiles.put(1L, m3);
      Userprofiles.put(2L, m4);
   }

   //Method to fetch all profile
   public List<UserProfile> getAllProfile() {
      List<UserProfile> list = new ArrayList<UserProfile>(Userprofiles.values());
      return list;
   }  // Method to fetch only one profile depending on the ID provided

   public UserProfile getProfile(long id) {
      return Userprofiles.get(id);
   }  //Method to add profile

   public UserProfile addProfile(UserProfile UserProfile) {
      UserProfile.setProId(Userprofiles.size()+1);
      Userprofiles.put(UserProfile.getProId(), UserProfile);
      return UserProfile;
   }  //method to update Profile

   public UserProfile UpdateProfile(UserProfile UserProfile) {
      if(UserProfile.getProId()<=0) {
         return null;
      } else {
         Userprofiles.put(UserProfile.getProId(), UserProfile);
         return UserProfile;
      }
   } //method to delete profile

   public void RemoveProfile(long Id) {
      Userprofiles.remove(Id);
   }
}

Step 11 − 在此步骤中,我们将创建将链接到 URL 的资源类,并将调用相应服务。

Step 11 − In this step, we will create our Resource class that will be linked with the URL and the corresponding service will be called.

package com.tutorialspoint.userprofile.Resource;

import com.tutorialspoint.userprofile.Model.UserProfile;
import com.tutorialspoint.userprofile.service.ProfileService;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/Profile")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)

public class ProfileResource {
   ProfileService messageService = new ProfileService();

   @GET
   public List<UserProfile> getProfile() {
      return messageService.getAllProfile();
   }

   @GET
   @Path("/{ProID}")
   public UserProfile getProfile(@PathParam("ProID")long Id) {
      return messageService.getProfile(Id);
   }

   @POST
   public UserProfile addProfile(UserProfile profile) {
      return messageService.addProfile(profile);
   }

   @PUT
   @Path("/{proID}")
   public UserProfile UpdateProfile(@PathParam("proID")long Id,UserProfile UserProfile) {
      UserProfile.setProId(Id);
      return messageService.UpdateProfile(UserProfile);
   }

   @DELETE
   @Path("/{ProID}")
   public void deleteProfile(@PathParam("ProID")long Id) {
      messageService.RemoveProfile(Id);
   }
}

Step 12 − 清理构建项目并运行它。如果一切顺利,那么您应该在访问 http://localhost:8080/UserProfile/webapi/Profile” URL 时在浏览器中获得以下输出。

Step 12 − Clean build the project and run it. If everything goes well then you should get the following output in the browser, while accessing http://localhost:8080/UserProfile/webapi/Profile” URL.

您可以看到使用 XML 表示填充了不同的条目。

You can see different entries are populated using XML representation.

user profiles

可以通过应用适当的方法 URL 使用 Postman 测试不同的方法。

Different method can be tested using Postman by applying proper method URL.

@GET method − 以下屏幕截图演示了我们如何获得 get 请求所需的返回所有用户详细信息的结果。

@GET method − The following screenshot demonstrates how we can get the desired result for get request, which returns all user details.

screenshot demonstrates

@POST − 以下请求可用于测试我们的发布方法。请注意 proId 已自动生成。

@POST − The following request can be used to test our Post method. Notice how the proId has been generated automatically.

post method

@PUT − 此方法将更新条目。下图演示了 Jersey 如何从请求 URL 中获取 proId 并更新相同用户配置文件回复。

@PUT − This method will update the entries. The following screenshot demonstrates how Jersey takes the proId from the request URL and updates the same user profile reply.

same user profile reply

您可以用相同方式检查您的 Web 服务中可用的其他方法。

In the same way, you can check for other methods available in your web services.

在上一部分中,我们开发了一项服务,将公开 CRUD 功能。现在,无论何时尝试在我们的应用程序中实现此服务,都需要创建此应用程序的客户端并将其附加到我们的应用程序中。在本章中,我们将学习如何使用微服务理念构建此功能。以下是使用上述步骤构建的应用程序的图表表示。

In the previous section, we have developed one service which will expose CRUD functionality. Now whenever we try to implement this service in our application, we need to create a client of this application and attach it to our application. In this chapter, we will learn how to build this functionality using the concept of Microservice. Following is a diagrammatic representation of our application built using the above steps.

actor

actor 应作为我们服务的入口点。在这种情况中,“ProfileResource.java”担当 actor 的作用。此类将调用不同的方法来执行不同的操作,例如添加、更新和删除。

The actor should be the entry point of our service. In this case “ProfileResource.java” performs the responsibility of an actor. This class will call different methods to perform different operations such as add, update and delete.

Decomposition of CRUD Application

根据微服务的核心原则,我们对每个模块只进行一项业务任务,因此一个 actor 不应负责所有四个 CRUD 功能。考虑以下示例,我们在其中引入了一些新的角色,以便您在概念上清楚了解微服务是 SOA 的架构表示。

According to the main principle of microservice, we need to have only one business task for each of the modules, hence one actor should not be responsible for all four CRUD functionalities. Consider the following example where we have introduced some new roles such that it will be conceptually clear to you that Microservice is an architectural representation of SOA.

architectural representation

“主用户”是与“应用程序控制器”通信以满足其需求的用户。“应用程序控制器”是根据最终用户请求只调用不同的“资源管理器”的用户。“资源管理器”执行需要完成的工作。让我们快速了解一下应用程序的不同单元的不同角色。

“Main user” is the user who communicates with the ”Application Controller” to serve one’s needs. “Application Controller” is the one who just calls different “Resource Managers” depending upon the request from the end user. “Resource Manager” does the job that is required to be done. Let’s take a quick look on the different roles of different units of the application.

  1. End User/Main Users − Requests for some resources to Application Controller.

  2. Application − Receives the request and forwards the same to specific Resource Manager.

  3. Resource Manager − Does the actual job of updating, deleting, and adding users.

看看一个类的全部责任是如何分布在其他不同类中的。

See how the total responsibility of one class is distributed among different other classes.

Microservice Architecture - Hands-On MSA

在本章中,我们将构建一个微服务应用程序,它将消耗不同的可用服务。我们都知道,微服务并不是构建应用程序的经济有效的方法,因为我们构建的每一项服务本质上都是全栈的。在本地环境中构建微服务需要高端系统配置,因为你需要四台服务器实例才能持续运行,以便在某一时间点能消耗它。为了构建我们有史以来的第一个微服务,我们将使用一些可用的 SOA 端点,并在我们的应用程序中消耗它们。

In this chapter, we will build one microservice application that will consume different available services. We all know that microservice is not a cost-effective way to build an application as each and every service we build will be full stack in nature. Building a microservice in the local environment would need high-end system configuration, as you need to have four instances of a server to keep running such that it can be consumed at a point of time. To build our first ever microservice, we will use some of the available SOA endpoints and we will consume the same in our application.

System Configuration and Setup

在进入构建阶段之前,请做好系统准备。你需要一些公共 Web 服务。你可以轻松地进行谷歌搜索。如果你想消耗 SOAP Web 服务,那么你将得到一个 WSDL 文件,然后你需要从中消耗特定的 Web 服务。对于 REST 服务,你只需要一个链接来消耗它。在这个示例中,你将把三个不同的 Web 服务“SOAP”、“REST”和“自定义”嵌入到一个应用程序中。

Before going further to the build phase, prepare your system accordingly. You would need some public web services. You can easily google for this. If you want to consume SOAP web service, then you will get one WSDL file and from there you need to consume the specific web service. For REST service, you will need only one link to consume the same. In this example, you will jam three different web services “SOAP”, “REST”, and “custom” in one application.

Application Architecture

你将使用微服务实现计划创建一个 Java 应用程序。你将创建一个自定义服务,此服务的输出将作为其他服务的输入。

You will create a Java application using microservice implementation plan. You will create a custom service and the output of this service will work as an input for other services.

下面是开发微服务应用程序的步骤。

Following are the steps to follow to develop a microservice application.

Step 1: Client creation for SOAP service − 有许多免费 Web API 可用于学习 Web 服务。为本教程的目的,使用“ http://www.webservicex.net/.” 的 GeoIP 服务。他们的网站上以“ webservicex.net. 提供了 WSDL 文件。要从该 WSDL 文件中生成客户端,你需要做的就是在你的终端中运行以下命令。

Step 1: Client creation for SOAP service − There are many free web APIs available to learn a web service. For the purpose of this tutorial, use the GeoIP service of “http://www.webservicex.net/.” The WSDL file is provided in the following link on their website “webservicex.net. To generate the client out of this WSDL file, all you need to do is run the following command in your terminal.

wsimport http://www.webservicex.net/geoipservice.asmx?WSDL

此命令将在一个名为“SEI”的文件夹(以服务端点接口命名)下生成所有必需的客户端文件。

This command will generate all the required client files under one folder named “SEI”, which is named after service end point interface.

Step 2: Create your custom web service − 按照本教程前面阶段中提到的相同过程,构建基于 Maven 的 REST api,名为“CustomRest”。完成后,你会找到一个名为“MyResource.java”的类。继续并使用以下代码更新此类。

Step 2: Create your custom web service − Follow the same process mentioned at an earlier stage in this tutorial and build a Maven-based REST api named “CustomRest”. Once complete, you will find a class named “MyResource.java”. Go ahead and update this class using the following code.

package com.tutorialspoint.customrest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("myresource")
public class MyResource {
   @GET
   @Produces(MediaType.TEXT_PLAIN)

   public String getIt() {
      return "IND|INDIA|27.7.65.215";
   }
}

一切完成后,请在本机服务器上运行此应用程序。你应该在浏览器中获得以下输出。

Once everything is complete, go ahead and run this application on the server. You should get the following output in the browser.

web service

这是 Web 服务器,它在被调用后返回一个字符串对象。这是一项输入服务,它提供可被其他应用程序消耗以生成记录的输入。

This is the web server, which returns one string object once it is called. This is the input service that provides inputs that can be consumed by other application to generate records.

Step 3: Configure another Rest API − 在此步骤中,消耗 services.groupkt.com. 可用的另一项 Web 服务。调用时,这将返回一个 JSON 对象。

Step 3: Configure another Rest API − In this step, consume another web service available at services.groupkt.com. This will return a JSON object when invoked.

Step 4: Create JAVA application − 通过选择“新项目”→“JAVA 项目”创建一个正常的 Java 应用程序,然后按如下截图所示单击“完成”。

Step 4: Create JAVA application − Create one normal Java application by selecting “New Project” → “JAVA project” and hit Finish as shown in the following screenshot.

java application

Step 5: Add the SOAP client − 在步骤 1 中,你创建了 SOAP Web 服务的客户端文件。继续将这些客户端文件添加到你当前的项目。成功添加客户端文件后,你的应用程序目录将如下所示。

Step 5: Add the SOAP client − In step 1, you have created the client file for the SOAP web service. Go ahead and add these client files to your current project. After successful addition of the client files, your application directory will be look the following.

soap web service

Step 6: Create your main app − 创建一个主类,你将在其中消耗所有这三个 Web 服务。右键单击源项目,并创建一个名为“MicroServiceInAction.java”的新类。接下来,从这里调用不同的 Web 服务。

Step 6: Create your main app − Create your main class where you will consume all of these three web services. Right-click on the source project and create a new class named “MicroServiceInAction.java”. Next task is to call different web services from this.

Step 7: Call your custom web service − 为此,继续添加以下代码集以实现调用自己的服务。

Step 7: Call your custom web service − For this, go ahead and add the following set of codes to implement calling your own service.

try {
   url = new URL("http://localhost:8080/CustomRest/webapi/myresource");
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Accept", "application/json");

   if (conn.getResponseCode() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
   }

   BufferedReader br = new BufferedReader(new InputStreamReader(
      (conn.getInputStream())));
   while ((output = br.readLine()) != null) {
      inputToOtherService = output;
   }
   conn.disconnect();

} catch (MalformedURLException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
}

Step 8: Consume SOAP Services − 你生成了客户端文件,但你不知道该在整个软件包中调用哪个方法?为此,你需要再次参考你用来生成客户端文件的 WSDL。每个 WSDL 文件都应有一个“wsdl:service”标签,搜索此标签。它应该是该 Web 服务的入口点。以下是该应用程序的服务端点。

Step 8: Consume SOAP Services − You have generated your client file but you don’t know which method should be called in that entire package? For this, you need to refer to the WSDL again, which you used to generate your client files. Every WSDL file should have one “wsdl:service” tag search for this tag. It should be your entry point of that web service. Following is the service endpoint of this application.

wsdl service

现在你需要在应用程序中实现此服务。以下是实现 SOAP Web 服务所需的 Java 代码集。

Now you need to implement this service in your application. Following is the set of Java code you need to implement your SOAP web service.

GeoIPService newGeoIPService = new GeoIPService();
GeoIPServiceSoap newGeoIPServiceSoap = newGeoIPService.getGeoIPServiceSoap();
GeoIP newGeoIP = newGeoIPServiceSoap.getGeoIP(Ipaddress);
// Ipaddress is output of our own web service.

System.out.println("Country Name from SOAP Webserivce ---"+newGeoIP.getCountryName());

Step 9: Consume REST web service − 到目前为止已经消耗了其中两项服务。在此步骤中,将在自定义 Web 服务的帮助下消耗另一项带有自定义 URL 的 REST Web 服务。请使用以下代码集执行此操作。

Step 9: Consume REST web service − Two of the services have been consumed till now. In this step, another REST web service with customized URL will be consumed with the help of your custom web service. Use the following set of code to do so.

String url1="http://services.groupkt.com/country/get/iso3code/";//customizing the Url
url1 = url1.concat(countryCode);

try {
   URL url = new URL(url1);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setRequestProperty("Accept", "application/json");

   if (conn.getResponseCode() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
   }

   BufferedReader br = new BufferedReader(new InputStreamReader(
      (conn.getInputStream())));
   while ((output = br.readLine()) != null) {
      System.out.println(output);
   }
   conn.disconnect();

} catch (MalformedURLException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
}

Step 10: Consume all services − 如果你正在运行“CustomRest”Web 服务且已连接到互联网,如果一切都已成功完成,那么以下内容应为你合并的主类。

Step 10: Consume all services − Considering your “CustomRest” web service is running and you are connected to Internet, if everything is completed successfully then following should be your consolidated main class.

package microserviceinaction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;

import net.webservicex.GeoIP;
import net.webservicex.GeoIPService;
import net.webservicex.GeoIPServiceSoap;

public class MicroServiceInAction {
   static URL url;
   static HttpURLConnection conn;
   static String output;
   static String inputToOtherService;
   static String countryCode;
   static String ipAddress;
   static String CountryName;
   public static void main(String[] args) {
      //consuming of your own web service
      try {
         url = new URL("http://localhost:8080/CustomRest/webapi/myresource");
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Accept", "application/json");

         if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
         }

         BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));
         while ((output = br.readLine()) != null) {
            inputToOtherService = output;
         }
         conn.disconnect();

      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      //Fetching IP address from the String and other information
      StringTokenizer st = new StringTokenizer(inputToOtherService);
      countryCode = st.nextToken("|");
      CountryName = st.nextToken("|");
      ipAddress = st.nextToken("|");

      // Call to SOAP web service with output of your web service---
      // getting the location of our given IP address
      String Ipaddress = ipAddress;
      GeoIPService newGeoIPService = new GeoIPService();
      GeoIPServiceSoap newGeoIPServiceSoap = newGeoIPService.getGeoIPServiceSoap();
      GeoIP newGeoIP = newGeoIPServiceSoap.getGeoIP(Ipaddress);
      System.out.println("Country Name from SOAP Webservice ---"+newGeoIP.getCountryName());

      // Call to REST API --to get all the details of our country
      String url1 = "http://services.groupkt.com/country/get/iso3code/"; //customizing the Url
      url1 = url1.concat(countryCode);

      try {
         URL url = new URL(url1);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Accept", "application/json");

         if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
         }

         BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));
         while ((output = br.readLine()) != null) {
            System.out.println(output);
         }

         conn.disconnect();
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

一旦运行此文件,你将看到控制台中的以下输出。你已成功开发了你的第一个微服务应用程序。

Once you run this file, you will see the following output in the console. You have successfully developed your first microservice application.

output in the console