持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情
原文标题: Ultra-Fast Microservices in Java: When Microstream Meets Open Liberty ,作者:Otavio Santana
当我们谈论创建可扩展的应用程序时,微服务已经成为一个流行语。但这还不足够,与任何软件架构决策一样,它有一个权衡和几个挑战。幸运的是,对于我们Java开发人员来说,有两种工具的组合使我们的生活更轻松:Microstream和MicroProfile。本文将介绍如何将Microstream和 Open Liberty 结合起来,以创建一个轻松稳定且超快速的微服务应用程序。
具有Open Liberty的微服务
微服务给我们软件工程师带来了一些挑战,特别是作为面对分布式系统的第一步。但这并不意味着我们是孤独的。事实上,有几种工具可以让我们在Java世界中的生活更轻松,尤其是MicroProfile。
MicroProfile的目标是针对微服务架构优化企业版 Java 。它基于Java EE / Jakarta EE标准以及专门用于微服务的API,如Rest Client,Configuration,Open API等。
Open Liberty就是这些实现之一,它以IBM为主要贡献者。Open Liberty 是一个轻量级的开放式框架,用于构建快速高效的云原生 Java 微服务。它为运行云原生应用和微服务提供了足够的运行时。
Microstream的数据持久性非常快
一旦我们谈论微服务,我们就会谈论分布式系统及其挑战,这种谈论在持久性层中将是相同的。
当你有更多关于业务的不确定信息时,我们应该有一个模型,甚至是无模式数据库。尽管如此,持久性层仍然存在很多问题,主要是因为它很难改变。
制作可扩展应用程序的秘诀之一是确保它是无状态的,但我们在持久性层中负担不起它。首先,数据库旨在保留信息及其状态。
使数据持久化层更自然的解决方案之一是直接与 Java 实体作为图形集成。这就是Microstream所做的。
Microstream通过纯Java实现超快的在内存中处理数据。它提供微秒级查询时间、低延迟数据访问、巨大的数据吞吐量和工作负载。因此,它节省了数据中心的大量CPU功耗,二氧化碳排放和成本。
显示代码
让我们将两者结合起来,打造一个超快的微服务。一旦主要目标是展示两者如何结合,我们将选择一个流畅的演示。在此示例中,我们将创建一个简单的 CRUD,其中包含产品、名称和评级,并将其导出为 Rest API。
第一步是创建MicroProfile骨架:它毫不费力且流畅,主要是因为我们可以使用MicroProfile启动器进行可视化配置。配置文件版本 4.1 、 Java 11 和 Open Liberty ,如下图所示
现在有了应用程序的骨架。下一步就是添加Microstream并使两者协同工作。幸运的是,有一个库可以通过CDI扩展集成两者。因此,任何具有CDI和MicroProfile Config的应用程序都可以借助此API工作。
请查看最新版本并将其添加到您的应用程序中。
<dependency>
<groupId>one.microstream</groupId>
<artifactId>microstream-integrations-cdi</artifactId>
<version>LAST_VERSION_HERE</version>
</dependency>
复制代码
骨架已设置,因此让我们从代码开始。模型是中心部分。一旦它是一个平滑的示例,我们将创建一个包含几个字段的产品实体。使用Microstream的主要建议是使用不可变实体。因此,我们将创建一个产品作为不可变的实体。
public class Product {
private final long id;
private final String name;
private final String description;
private final int rating;
@JsonbCreator
public Product(
@JsonbProperty("id") final long id,
@JsonbProperty("name") final String name,
@JsonbProperty("description") final String description,
@JsonbProperty("rating") final int rating
) {
this.id = id;
this.name = name;
this.description = description;
this.rating = rating;
}
复制代码
JSON 注释仅告知 MicroProfile 如何将实体序列化为 JSON。
下一步是定义产品集合,我们称之为“库存”。库存类是一组具有多种操作方法的产品。
此类是实体与Microstream引擎之间的链接。与Microstream的连接是使用注释Storage 。
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import one.microstream.integrations.cdi.types.Storage;
@Storage
public class Inventory {
private final Set<Product> products = new HashSet<>();
public void add(final Product product) {
Objects.requireNonNull(product, "product is required");
this.products.add(product);
}
public Set<Product> getProducts() {
return Collections.unmodifiableSet(this.products);
}
public Optional<Product> findById(final long id) {
return this.products.stream().filter(this.isIdEquals(id)).limit(1).findFirst();
}
public void deleteById(final long id) {
this.products.removeIf(this.isIdEquals(id));
}
private Predicate<Product> isIdEquals(final long id) {
return p -> p.getId() == id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Inventory inventory = (Inventory) o;
return Objects.equals(products, inventory.products);
}
@Override
public int hashCode() {
return Objects.hash(products);
}
@Override
public String toString() {
return "Inventory{" +
"products=" + products +
'}';
}
}
复制代码
集合准备就绪后,让我们创建存储库。要使用我们的类,我们可以使用 CDI 中的注释。我们需要将此操作提交到将要更改此集合的每个操作中。对于任何更改库存的方法,都有一个InventoryInjectStore注释为我们自动处理它。
public interface ProductRepository
{
Collection<Product> getAll();
Product save(Product item);
Optional<Product> findById(long id);
void deleteById(long id);
}
@ApplicationScoped
public class ProductRepositoryStorage implements ProductRepository {
private static final Logger LOGGER = Logger.getLogger(ProductRepositoryStorage.class.getName());
@Inject
private Inventory inventory;
@Override
public Collection<Product> getAll() {
return this.inventory.getProducts();
}
@Override
@Store
public Product save(final Product item) {
this.inventory.add(item);
return item;
}
@Override
public Optional<Product> findById(final long id) {
LOGGER.info("Finding the item by id: " + id);
return this.inventory.findById(id);
}
@Override
@Store
public void deleteById(final long id) {
this.inventory.deleteById(id);
}
}
复制代码
最后一步是将此产品公开为 Rest API。然后,我们将使用Jakarta EE API返回MicroProfile:JAX-RS。接下来,我们将使用 MicroProfile 创建 Open API 文档。
@RequestScoped
@Path("products")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ProductController
{
@Inject
private ProductRepository repository;
// TODO don't worried about pagination
@GET
@Operation(summary = "Get all products", description = "Returns all available items at the restaurant")
@APIResponse(responseCode = "500", description = "Server unavailable")
@APIResponse(responseCode = "200", description = "The products")
@Tag(name = "BETA", description = "This API is currently in beta state")
@APIResponse(description = "The products", responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = Collection.class, readOnly = true, description = "the products", required = true, name = "products")))
public Collection<Product> getAll()
{
return this.repository.getAll();
}
@GET
@Path("{id}")
@Operation(summary = "Find a product by id", description = "Find a product by id")
@APIResponse(responseCode = "200", description = "The product")
@APIResponse(responseCode = "404", description = "When the id does not exist")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Tag(name = "BETA", description = "This API is currently in beta state")
@APIResponse(description = "The product", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = Product.class)))
public Product findById(
@Parameter(description = "The item ID", required = true, example = "1", schema = @Schema(type = SchemaType.INTEGER)) @PathParam("id") final long id)
{
return this.repository.findById(id).orElseThrow(
() -> new WebApplicationException("There is no product with the id " + id, Response.Status.NOT_FOUND));
}
@POST
@Operation(summary = "Insert a product", description = "Insert a product")
@APIResponse(responseCode = "201", description = "When creates an product")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Tag(name = "BETA", description = "This API is currently in beta state")
public Response insert(
@RequestBody(description = "Create a new product.", Content = @Content(mediaType = "application/json", schema = @Schema(implementation = Product.class))) final Product product)
{
return Response.status(Response.Status.CREATED).entity(this.repository.save(product)).build();
}
@DELETE
@Path("{id}")
@Operation(summary = "Delete a product by ID", description = "Delete a product by ID")
@APIResponse(responseCode = "200", description = "When deletes the product")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Tag(name = "BETA", description = "This API is currently in beta state")
public Response delete(
@Parameter(description = "The item ID", required = true, example = "1", schema = @Schema(type = SchemaType.INTEGER)) @PathParam("id") final long id)
{
this.repository.deleteById(id);
return Response.status(Response.Status.NO_CONTENT).build();
}
}
复制代码
就是这样,我们可以测试正在运行的应用程序并检查结果。
mvn clean package
java -jar target/openliberty-example.jar
curl --location --request POST 'http://localhost:8080/products/' \
--header 'Content-Type: application/json' \
--data-raw '{"id": 1, "name": "banana", "description": "a fruit", "rating": 5}'
curl --location --request POST 'http://localhost:8080/products/' \
--header 'Content-Type: application/json' \
--data-raw '{"id": 2, "name": "watermelon", "description": "watermelon sugar ahh", "rating": 4}'
curl --location --request GET 'http://localhost:8080/products/'
curl --location --request GET 'http://localhost:8080/products/1'
复制代码
我们终于在Open Liberty和Microstream之间实现了集成。本教程展示了两者如何协同工作,并为您提供了一个面对持久性问题的新工具:Microstream。事实上,当你想要创建微服务来超快速运行它时,Microstream和Open Liberty就是伟大的盟友。