Building a Microservice with Apache Meecrowave – 用Apache Meecrowave构建一个微服务

最后修改: 2018年 7月 8日

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

 

1. Overview

1.概述

In this tutorial, we’ll explore the basic functionality of the Apache Meecrowave framework.

在本教程中,我们将探讨Apache Meecrowave框架的基本功能。

Meecrowave is a lightweight microservices framework from Apache, which works very well with CDI, JAX-RS, and JSON API’s. It’s very simple to setup and deploy. It also eliminates the hassle of deploying heavy application servers like Tomcat, Glassfish, Wildfly, etc.

Meecrowave是Apache的一个轻量级微服务框架,它与CDI、JAX-RS和JSON API的配合非常好。它的设置和部署非常简单。它还消除了部署Tomcat、Glassfish、Wildfly等重型应用服务器的麻烦。

2. Maven Dependency

2.Maven的依赖性

To use Meecrowave, let’s define the dependency in pom.xml:

为了使用Meecrowave,让我们在pom.xml中定义依赖性:

<dependency>
    <groupId>org.apache.meecrowave</groupId>
    <artifactId>meecrowave-core</artifactId>
    <version>1.2.1</version>
</dependency>

Check for the latest version on Maven Central.

Maven Central上查看最新版本。

3. Starting a Simple Server

3.启动一个简单的服务器

I order to start a Meecrowave server all we need to do is write the main method, create a Meecrowave instance and invoke the main bake() method:

为了启动一个Meecrowave服务器,我们需要做的就是编写main方法,创建一个Meecrowave实例,并调用主bake() 方法

public static void main(String[] args) {
    try (Meecrowave meecrowave = new Meecrowave()) {
        meecrowave.bake().await();
    }
}

We don’t need this main method if we package the application as a distribution package; we’ll look into that in the later sections. The main class is useful while testing the application from an IDE.

如果我们把应用程序打包成一个发行包,就不需要这个主方法;我们将在后面的章节中研究这个问题。主类在从IDE中测试应用程序时很有用。

As an advantage, while developing in an IDE, once we run the application using the main class, it reloads automatically with code changes, thus saving the hassle of restarting the server again and again to test.

作为一个优势,在IDE中开发时,一旦我们使用主类运行应用程序,它就会随着代码的变化自动重新加载,从而省去了一次又一次重启服务器进行测试的麻烦。

Note that, if we are using Java 9, don’t forget to add javax.xml.bind modules to the VM:

注意,如果我们使用的是Java 9,别忘了在虚拟机中添加javax.xml.bind模块。

--add-module javax.xml.bind

Creating the server this way will start it with default configuration. We can programmatically update the default configurations using the Meecrowave.Builder class:

以这种方式创建服务器将以默认配置启动它。我们可以使用Meecrowave.Builder以编程方式更新默认配置。

Meecrowave.Builder builder = new Meecrowave.Builder();
builder.setHttpPort(8080);
builder.setScanningPackageIncludes("com.baeldung.meecrowave");
builder.setJaxrsMapping("/api/*");
builder.setJsonpPrettify(true);

And use this builder instance while baking the server:

并在烘烤服务器时使用这个builder实例。

try (Meecrowave meecrowave = new Meecrowave(builder)) { 
    meecrowave.bake().await();
}

There are more configurable properties here.

有更多可配置的属性这里

4. REST Endpoints

4.REST端点

Now, once the server is ready, let’s create some REST endpoints:

现在,一旦服务器准备好了,让我们创建一些REST端点。

@RequestScoped
@Path("article")
public class ArticleEndpoints {
    
    @GET
    public Response getArticle() {
        return Response.ok().entity(new Article("name", "author")).build();      
    }
    
    @POST 
    public Response createArticle(Article article) { 
        return Response.status(Status.CREATED).entity(article).build(); 
    }
}

Notice that, we’re mostly using JAX-RS annotations to create the REST endpoints. Read more about JAX-RS here.

请注意,我们主要使用JAX-RS注释来创建REST端点。请阅读有关JAX-RS的更多信息这里

In the next section, we’ll see how to test these endpoints.

在下一节,我们将看到如何测试这些端点。

5. Testing

5.测试

Writing unit test cases with for REST API’s written with Meecrowave is simple as writing annotated JUnit test cases.

用Meecrowave编写的REST API的单元测试用例,就像编写注解的JUnit测试用例一样简单。

Let’s add the test dependencies to our pom.xml first:

让我们先把测试依赖添加到我们的pom.xml中。

<dependency>
    <groupId>org.apache.meecrowave</groupId>
    <artifactId>meecrowave-junit</artifactId>
    <version>1.2.1</version>
    <scope>test</scope>
</dependency>

To see the latest version, check out Maven Central.

要查看最新版本,请查看Maven Central

Also, let’s add OkHttp as HTTP client for our tests:

另外,让我们添加OkHttp作为我们测试的HTTP客户端。

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>

Check out the latest version here.

请查看最新版本这里

Now with the dependencies in place lets go ahead and write the tests:

现在,随着依赖关系的建立,让我们继续写测试。

@RunWith(MonoMeecrowave.Runner.class)
public class ArticleEndpointsIntegrationTest {
    
    @ConfigurationInject
    private Meecrowave.Builder config;
    private static OkHttpClient client;
    
    @BeforeClass
    public static void setup() {
        client = new OkHttpClient();
    }
    
    @Test
    public void whenRetunedArticle_thenCorrect() {
        String base = "http://localhost:" + config.getHttpPort();
        
        Request request = new Request.Builder()
          .url(base + "/article")
          .build();
        Response response = client.newCall(request).execute();
        assertEquals(200, response.code());
    }
}

While writing the test cases, make to annotate the test class with MonoMeecrowave.Runner class, also inject the configuration, to get access to the random port used by Meecrowave for the test server

在编写测试用例时,用MonoMeecrowave.Runner类来注释测试类,同时注入配置,以获得Meecrowave用于测试服务器的随机端口的访问权。

6. Dependency Injection

6.依赖性注入

To inject dependencies into a class, we need to annotate those classes within a particular scope.

为了向一个类注入依赖关系,我们需要在一个特定的范围内对这些类进行注释。

Let’s take the example of an ArticleService class:

让我们以ArticleService类为例。

@ApplicationScoped
public class ArticleService {
    public Article createArticle(Article article) {
        return article;
    }
}

Now let’s inject this into our ArticleEndpoints instance using the javax.inject.Inject annotation:

现在,让我们使用javax.inject.Injectannotation将其注入我们的ArticleEndpointsinstance:

@Inject
ArticleService articleService;

7. Packaging the Application

7.对申请进行包装

Creating a distribution package becomes very simple, with the Meecrowave Maven plugin:

有了Meecrowave Maven插件,创建分发包变得非常简单。

<build>
    ...
    <plugins>
        <plugin>
            <groupId>org.apache.meecrowave</groupId>
            <artifactId>meecrowave-maven-plugin</artifactId>
            <version>1.2.1</version>
        </plugin>
    </plugins>
</build>

Once we have the plugin in place let’s use the Maven goal meecrowave:bundle to package the application.

一旦我们有了这个插件,我们就可以使用Maven目标meecrowave:bundle来打包应用程序

Once packaged it will create a zip inside the target directory:

一旦打包,它将在目标目录下创建一个压缩包。

meecrowave-meecrowave-distribution.zip

This zip contains the required artifacts to deploy the application:

这个压缩包包含部署应用程序所需的工件。

|____meecrowave-distribution
| |____bin
| | |____meecrowave.sh
| |____logs
| | |____you_can_safely_delete.txt
| |____lib
| |____conf
| | |____log4j2.xml
| | |____meecrowave.properties

Let’s navigate to the bin directory and start the application:

让我们导航到bin目录并启动该应用程序。

./meecrowave.sh start

To stop the application:

要停止应用。

./meecrowave.sh stop

8. Conclusion

8.结语

In this article, we learned about using Apache Meecrowave to create a microservice. Also, we looked into some basic configuration about the application and to prepare a distribution package.

在这篇文章中,我们了解了如何使用Apache Meecrowave来创建一个微服务。此外,我们还研究了一些关于应用程序的基本配置,并准备了一个分发包。

As always the code snippets could be found in the Github Project.

一如既往,代码片段可以在Github项目中找到。