Building Microservices with Eclipse MicroProfile – 用Eclipse MicroProfile构建微服务

最后修改: 2018年 2月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll focus on building a microservice based on Eclipse MicroProfile.

在这篇文章中,我们将专注于构建一个基于Eclipse MicroProfile的微服务。

We’ll look at how to write a RESTful web application using JAX-RS, CDI and JSON-P APIs.

我们将研究如何使用JAX-RS、CDI和JSON-P API编写一个RESTful Web应用。

2. A Microservice Architecture

2.微服务架构

Simply put, microservices are a software architecture style that forms a complete system as a collection of several independent services.

简单地说,微服务是一种软件架构风格,它将一个完整的系统作为若干独立服务的集合。

Each one focuses on one functional perimeter and communicates to the others with a language-agnostic protocol, such as REST.

每个人都专注于一个功能区,并通过语言无关的协议(如REST)与其他功能区进行通信。

3. Eclipse MicroProfile

3.Eclipse MicroProfile

Eclipse MicroProfile is an initiative that aims to optimize Enterprise Java for the Microservices architecture. It’s based on a subset of Jakarta EE WebProfile APIs, so we can build MicroProfile applications like we build Jakarta EE ones.

Eclipse MicroProfile是一项旨在为微服务架构优化企业Java的倡议。它基于Jakarta EE WebProfile APIs的一个子集,因此我们可以像构建Jakarta EE应用程序一样构建MicroProfile应用程序。

The goal of MicroProfile is to define standard APIs for building microservices and deliver portable applications across multiple MicroProfile runtimes.

MicroProfile的目标是为构建微服务定义标准的API,并在多个MicroProfile运行时提供可移植的应用程序。

4. Maven Dependencies

4.Maven的依赖性

All dependencies required to build an Eclipse MicroProfile application are provided by this BOM (Bill Of Materials) dependency:

构建Eclipse MicroProfile应用程序所需的所有依赖性都由这个BOM(Bill Of Materials)依赖性提供。

<dependency>
    <groupId>org.eclipse.microprofile</groupId>
    <artifactId>microprofile</artifactId>
    <version>1.2</version>
    <type>pom</type>
    <scope>provided</scope>
</dependency>

The scope is set as provided because the MicroProfile runtime already includes the API and the implementation.

范围被设置为provided,因为MicroProfile运行时已经包括API和实现。

5. Representation Model

5.代表性模型

Let’s start by creating a quick resource class:

让我们从创建一个快速资源类开始。

public class Book {
    private String id;
    private String name;
    private String author;
    private Integer pages;
    // ...
}

As we can see, there’s no annotation on this Book class.

我们可以看到,这个Book类上没有注解。

6. Using CDI

6.使用CDI

Simply put, CDI is an API that provides dependency injection and lifecycle management. It simplifies the use of Enterprise beans in Web Applications.

简单地说,CDI是一个提供依赖性注入和生命周期管理的API。它简化了Web应用中企业Bean的使用。

Let’s now create a CDI managed bean as a store for the book representation:

现在让我们创建一个CDI管理的bean,作为书的表示的存储。

@ApplicationScoped
public class BookManager {

    private ConcurrentMap<String, Book> inMemoryStore
      = new ConcurrentHashMap<>();

    public String add(Book book) {
        // ...
    }

    public Book get(String id) {
        // ...
    }

    public List getAll() {
        // ...
    }
}

We annotate this class with @ApplicationScoped because we need only one instance whose state is shared by all clients. For that, we used a ConcurrentMap as a type-safe in-memory data store. Then we added methods for CRUD operations.

我们用@ApplicationScoped来注解这个类,因为我们只需要一个实例,其状态被所有客户端共享。为此,我们使用一个ConcurrentMap作为类型安全的内存数据存储。然后我们添加了CRUD操作的方法。

Now our bean is a CDI ready and can be injected into the bean BookEndpoint using the @Inject annotation.

现在我们的Bean是CDI就绪,可以使用@Inject注解注入到Bean BookEndpoint。

7. JAX-RS API

7.JAX-RS API

To create a REST application with JAX-RS, we need to create an Application class annotated with @ApplicationPath and a resource annotated with @Path.

为了用JAX-RS创建一个REST应用程序,我们需要创建一个用@ApplicationPath注释的Application类和一个用@Path注释的资源。

7.1. JAX RS Application

7.1.JAX RS应用程序

The JAX-RS Application identifies the base URI under which we expose the resource in a Web Application.

JAX-RS 应用程序确定了基础 URI,我们在 Web 应用程序中使用该资源。

Let’s create the following JAX-RS Application:

让我们创建以下JAX-RS应用程序。

@ApplicationPath("/library")
public class LibraryApplication extends Application {
}

In this example, all JAX-RS resource classes in the Web Application are associated with the LibraryApplication making them under the same library path, that’s the value of the ApplicationPath annotation.

在这个例子中,Web 应用程序中的所有 JAX-RS 资源类都与 LibraryApplication 相关联,使它们处于同一个 library 路径之下,这就是 ApplicationPath 注解的值。

This annotated class tells the JAX RS runtime that it should find resources automatically and exposes them.

这个注解的类告诉JAX RS运行时,它应该自动找到资源并公开它们。

7.2. JAX RS Endpoint

7.2.JAX RS端点

An Endpoint class, also called Resource class, should define one resource although many of the same types are technically possible.

一个端点类,也叫资源类,应该定义一个资源,尽管技术上有许多相同的类型。

Each Java class annotated with @Path, or having at least one method annotated with @Path or @HttpMethod is an Endpoint.

每个用@Path注解的Java类,或至少有一个用@Path或@HttpMethod注解的方法,都是一个Endpoint。

Now, we’ll create a JAX-RS Endpoint that exposes that representation:

现在,我们将创建一个JAX-RS端点,公开该表示。

@Path("books")
@RequestScoped
public class BookEndpoint {

    @Inject
    private BookManager bookManager;
 
    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBook(@PathParam("id") String id) {
        return Response.ok(bookManager.get(id)).build();
    }
 
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllBooks() {
        return Response.ok(bookManager.getAll()).build();
    }
 
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response add(Book book) {
        String bookId = bookManager.add(book);
        return Response.created(
          UriBuilder.fromResource(this.getClass())
            .path(bookId).build())
            .build();
    }
}

At this point, we can access the BookEndpoint Resource under the /library/books path in the web application.

在这一点上,我们可以访问Web应用程序中/library/books路径下的BookEndpoint资源。

7.3. JAX RS JSON Media Type

7.3. JAX RS JSON媒体类型

JAX RS supports many media types for communicating with REST clients, but Eclipse MicroProfile restricts the use of JSON as it specifies the use of the JSOP-P API. As such, we need to annotate our methods with @Consumes(MediaType.APPLICATION_JSON) and @Produces(MediaType.APPLICATION_JSON).

JAX RS支持许多媒体类型来与REST客户端通信,但是Eclipse MicroProfile限制使用JSON,因为它指定使用JSOP-P API。因此,我们需要用@Consumes(MediaType.APPLICATION_JSON)和@Produces(MediaType.APPLICATION_JSON)来注释我们的方法。

The @Consumes annotation restricts the accepted formats – in this example, only JSON data format is accepted. The HTTP request header Content-Type should be application/json.

@Consumes注解限制了接受的格式–在这个例子中,只接受JSON数据格式。HTTP请求头Content-Type应该是application/json

The same idea lies behind the @Produces annotation. The JAX RS Runtime should marshal the response to JSON format. The request HTTP header Accept should be application/json.

@Produces 注解的背后也有同样的想法。JAX RS Runtime 应该将响应整理成 JSON 格式。请求的 HTTP 标头 Accept 应该是 application/json.

8. JSON-P

8.JSON-P

JAX RS Runtime supports JSON-P out of the box so that we can use JsonObject as a method input parameter or return type.

JAX RS Runtime开箱即支持JSON-P,因此我们可以使用JsonObject作为方法的输入参数或返回类型。

But in the real world, we often work with POJO classes. So we need a way to do the mapping between JsonObject and POJO. Here’s where the JAX RS entity provider goes to play.

但在现实世界中,我们经常与POJO类打交道。所以我们需要一种方法来完成JsonObject和POJO之间的映射。这里就是JAX RS实体提供者发挥作用的地方。

For marshaling JSON input stream to the Book POJO, that’s invoking a resource method with a parameter of type Book, we need to create a class BookMessageBodyReader:

为了将JSON输入流汇集到Book POJO,即调用一个参数类型为Book的资源方法,我们需要创建一个BookMessageBodyReader:类。

@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class BookMessageBodyReader implements MessageBodyReader<Book> {

    @Override
    public boolean isReadable(
      Class<?> type, Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType) {
 
        return type.equals(Book.class);
    }

    @Override
    public Book readFrom(
      Class type, Type genericType, 
      Annotation[] annotations,
      MediaType mediaType, 
      MultivaluedMap<String, String> httpHeaders, 
      InputStream entityStream) throws IOException, WebApplicationException {
 
        return BookMapper.map(entityStream);
    }
}

We do the same process to unmarshal a Book to JSON output stream, that’s invoking a resource method whose return type is Book, by creating a BookMessageBodyWriter:

我们通过创建一个BookMessageBodyWriter:来完成解密Book到JSON输出流的同样过程,即调用一个返回类型为Book的资源方法。

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookMessageBodyWriter 
  implements MessageBodyWriter<Book> {
 
    @Override
    public boolean isWriteable(
      Class<?> type, Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType) {
 
        return type.equals(Book.class);
    }
 
    // ...
 
    @Override
    public void writeTo(
      Book book, Class<?> type, 
      Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType, 
      MultivaluedMap<String, Object> httpHeaders, 
      OutputStream entityStream) throws IOException, WebApplicationException {
 
        JsonWriter jsonWriter = Json.createWriter(entityStream);
        JsonObject jsonObject = BookMapper.map(book);
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
    }
}

As BookMessageBodyReader and BookMessageBodyWriter are annotated with @Provider, they’re registered automatically by the JAX RS runtime.

由于 BookMessageBodyReaderBookMessageBodyWriter 被注释为 @Provider,它们被 JAX RS 运行时间自动注册。

9. Building and Running the Application

9.构建和运行应用程序

A MicroProfile application is portable and should run in any compliant MicroProfile runtime. We’ll explain how to build and run our application in Open Liberty, but we can use any compliant Eclipse MicroProfile.

MicroProfile应用程序是可移植的,应该在任何兼容的MicroProfile运行时运行。我们将解释如何在Open Liberty中构建和运行我们的应用程序,但我们可以使用任何兼容的Eclipse MicroProfile。

We configure Open Liberty runtime through a config file server.xml:

我们通过配置文件server.xml配置Open Liberty运行时。

<server description="OpenLiberty MicroProfile server">
    <featureManager>
        <feature>jaxrs-2.0</feature>
        <feature>cdi-1.2</feature>
        <feature>jsonp-1.0</feature>
    </featureManager>
    <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
      id="defaultHttpEndpoint" host="*"/>
    <applicationManager autoExpand="true"/>
    <webApplication context-root="${app.context.root}" location="${app.location}"/>
</server>

Let’s add the plugin liberty-maven-plugin to our pom.xml:

让我们把插件liberty-maven-plugin加入我们的pom.xml。

<?xml version="1.0" encoding="UTF-8"?>
<plugin>
    <groupId>net.wasdev.wlp.maven.plugins</groupId>
    <artifactId>liberty-maven-plugin</artifactId>
    <version>2.1.2</version>
    <configuration>
        <assemblyArtifact>
            <groupId>io.openliberty</groupId>
            <artifactId>openliberty-runtime</artifactId>
            <version>17.0.0.4</version>
            <type>zip</type>
        </assemblyArtifact>
        <configFile>${basedir}/src/main/liberty/config/server.xml</configFile>
        <packageFile>${package.file}</packageFile>
        <include>${packaging.type}</include>
        <looseApplication>false</looseApplication>
        <installAppPackages>project</installAppPackages>
        <bootstrapProperties>
            <app.context.root>/</app.context.root>
            <app.location>${project.artifactId}-${project.version}.war</app.location>
            <default.http.port>9080</default.http.port>
            <default.https.port>9443</default.https.port>
        </bootstrapProperties>
    </configuration>
    <executions>
        <execution>
            <id>install-server</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>install-server</goal>
                <goal>create-server</goal>
                <goal>install-feature</goal>
            </goals>
        </execution>
        <execution>
            <id>package-server-with-apps</id>
            <phase>package</phase>
            <goals>
                <goal>install-apps</goal>
                <goal>package-server</goal>
            </goals>
        </execution>
    </executions>
</plugin>

This plugin is configurable throw a set of properties:

这个插件是可以配置的,抛出一组属性。

<properties>
    <!--...-->
    <app.name>library</app.name>
    <package.file>${project.build.directory}/${app.name}-service.jar</package.file>
    <packaging.type>runnable</packaging.type>
</properties>

The exec goal above produces an executable jar file so that our application will be an independent microservice which can be deployed and run in isolation. We can also deploy it as Docker image.

上面的exec目标产生了一个可执行的jar文件,这样我们的应用程序将是一个独立的微服务,可以被部署和隔离运行。我们也可以将其部署为Docker镜像。

To create an executable jar, run the following command:

要创建一个可执行的jar,运行以下命令。

mvn package

And to run our microservice, we use this command:

而为了运行我们的微服务,我们使用这个命令。

java -jar target/library-service.jar

This will start the Open Liberty runtime and deploy our service. We can access to our Endpoint and getting all books at this URL:

这将启动Open Liberty运行时间并部署我们的服务。我们可以访问我们的端点,并在这个URL上获得所有书籍。

curl http://localhost:9080/library/books

The result is a JSON:

其结果是一个JSON。

[
  {
    "id": "0001-201802",
    "isbn": "1",
    "name": "Building Microservice With Eclipse MicroProfile",
    "author": "baeldung",
    "pages": 420
  }
]

To get a single book, we request this URL:

要想获得一本书,我们需要这个网址。

curl http://localhost:9080/library/books/0001-201802

And the result is JSON:

而结果是JSON。

{
    "id": "0001-201802",
    "isbn": "1",
    "name": "Building Microservice With Eclipse MicroProfile",
    "author": "baeldung",
    "pages": 420
}

Now we’ll add a new Book by interacting with the API:

现在我们将通过与API的交互来添加一个新的图书。

curl 
  -H "Content-Type: application/json" 
  -X POST 
  -d '{"isbn": "22", "name": "Gradle in Action","author": "baeldung","pages": 420}' 
  http://localhost:9080/library/books

As we can see, the status of the response is 201, indicating that the book was successfully created, and the Location is the URI by which we can access it:

我们可以看到,响应的状态是201,表明书被成功创建,而Location是我们可以访问它的URI。

< HTTP/1.1 201 Created
< Location: http://localhost:9080/library/books/0009-201802

10. Conclusion

10.结论

This article demonstrated how to build a simple microservice based on Eclipse MicroProfile, discussing JAX RS, JSON-P and CDI.

本文演示了如何基于Eclipse MicroProfile构建一个简单的微服务,讨论了JAX RS、JSON-P和CDI。

The code is available over on Github; this is a Maven-based project, so it should be simple to import and run as it is.

该代码可在Github上获得;这是一个基于Maven的项目,所以应该可以简单地导入和运行它。