Helidon案例

wen java案例 2

本文目录导读:

Helidon案例

  1. 案例一:快速构建 RESTful 服务(Helidon SE 风格)
  2. 案例二:连接数据库 + JPA(企业级标准,Helidon MP 风格)
  3. 案例三:微服务调用 + 容错(结合 Service Registry)
  4. 案例四:配置文件管理(YAML)
  5. 案例五:优雅停机 + 健康检查(生产必备)
  6. 对比总结:SE vs MP 怎么选?
  7. 最佳实践建议

Helidon 是 Oracle 推出的一个开源微服务框架,基于 Java 构建,有两种风格:Helidon SE(函数式编程,轻量级)和 Helidon MP(MicroProfile 规范,类似 Spring Boot 的注解风格)。

为了给你最实用的参考,这里整理了几个典型的生产级案例场景,并提供可运行的核心代码示例,你可以直接复制这些代码进行学习和测试。


快速构建 RESTful 服务(Helidon SE 风格)

场景:用户管理服务的增删改查接口。 特点:极简、响应式、启动时间极短(毫秒级)。

步骤 1:创建 Maven 依赖(pom.xml)

<dependencies>
    <dependency>
        <groupId>io.helidon.webserver</groupId>
        <artifactId>helidon-webserver</artifactId>
        <version>4.0.0</version>
    </dependency>
    <!-- 配置管理 -->
    <dependency>
        <groupId>io.helidon.config</groupId>
        <artifactId>helidon-config-yaml</artifactId>
        <version>4.0.0</version>
    </dependency>
</dependencies>

步骤 2:主程序代码(Main.java)

import io.helidon.webserver.WebServer;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.http.HttpService;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;
import io.helidon.common.http.Http;
public class Main {
    public static void main(String[] args) {
        // 启动服务(使用链式调用绑定路由)
        WebServer.builder()
                .port(8080)
                .routing(rules -> rules
                        .get("/hello", (req, res) -> res.send("Hello Helidon SE!"))
                        .get("/users/{id}", Main::getUser)  // 路径参数
                        .post("/users", Main::createUser)   // POST 请求
                )
                .build()
                .start();
        System.out.println("服务已启动: http://localhost:8080/hello");
    }
    // 根据ID查询用户(路径参数示例)
    private static void getUser(ServerRequest req, ServerResponse res) {
        String id = req.path().pathParameters().get("id");
        // 模拟数据库查询
        res.send("查询用户ID: " + id);
    }
    // 创建用户(接收JSON示例)
    private static void createUser(ServerRequest req, ServerResponse res) {
        String body = req.content().as(String.class);
        res.status(Http.Status.CREATED_201)
           .send("创建用户数据: " + body);
    }
}

测试命令

curl http://localhost:8080/hello
curl http://localhost:8080/users/123
curl -X POST -d '{"name":"张三"}' http://localhost:8080/users

连接数据库 + JPA(企业级标准,Helidon MP 风格)

场景:典型的订单管理模块,使用 JPA + 连接池。 特点:与 Spring Boot 写法非常相似,适合团队协作。

步骤 1:依赖(pom.xml)

<dependencies>
    <!-- MicroProfile 核心 -->
    <dependency>
        <groupId>io.helidon.microprofile</groupId>
        <artifactId>helidon-microprofile-core</artifactId>
        <version>4.0.0</version>
    </dependency>
    <!-- JPA 支持 -->
    <dependency>
        <groupId>io.helidon.integrations.cdi</groupId>
        <artifactId>helidon-integrations-cdi-jpa</artifactId>
        <version>4.0.0</version>
    </dependency>
    <!-- H2 内存数据库 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.2.224</version>
    </dependency>
</dependencies>

步骤 2:实体类(Order.java)

import javax.persistence.*;
@Entity
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "product_name")
    private String productName;
    private Double price;
    // 省略 getter/setter 构造函数...
}

步骤 3:数据仓库接口

import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
@ApplicationScoped
public class OrderRepository {
    @PersistenceContext
    private EntityManager em;
    @Transactional
    public Order save(Order order) {
        return em.merge(order);
    }
    public List<Order> findAll() {
        return em.createQuery("SELECT o FROM Order o", Order.class).getResultList();
    }
}

步骤 4:REST 接口(OrderResource.java)

import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import javax.inject.Inject;
@Path("/orders")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class OrderResource {
    @Inject
    private OrderRepository repository;
    @GET
    public List<Order> getAll() {
        return repository.findAll();
    }
    @POST
    public Response create(Order order) {
        Order saved = repository.save(order);
        return Response.status(Response.Status.CREATED).entity(saved).build();
    }
}

微服务调用 + 容错(结合 Service Registry)

场景:当需要调用其他微服务时,如何使用 Helidon 实现声明式的 HTTP 客户端和熔断。

核心代码(使用 Helidon MP 的 REST 客户端):

import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
// 定义远程服务接口
@RegisterRestClient(baseUri = "http://localhost:7001")  // 目标服务地址
public interface RemoteService {
    @GET
    @Path("/api/data")
    String getRemoteData();
}
// 在业务代码中注入调用
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.eclipse.microprofile.faulttolerance.Fallback;
import javax.inject.Inject;
@Path("/consume")
public class ConsumerResource {
    @Inject
    @RestClient
    private RemoteService remoteService;
    @GET
    @Fallback(fallbackMethod = "onFailure")  // 熔断降级
    public String callRemote() {
        return remoteService.getRemoteData();
    }
    // 降级方法
    public String onFailure() {
        return "远程服务不可用,返回缓存数据";
    }
}

配置文件管理(YAML)

Helidon 的配置中心是其特色,支持环境变量覆盖、多环境切换。

配置文件application.yaml

server:
  port: 8080
  host: 0.0.0.0
app:
  name: "订单服务"
  version: "1.0.0"
  database:
    url: "jdbc:h2:mem:test"
    user: "sa"
    password: ""

在代码中读取配置

import org.eclipse.microprofile.config.inject.ConfigProperty;
import javax.inject.Inject;
public class ConfigService {
    @Inject
    @ConfigProperty(name = "app.version")
    private String version;  // 自动读取版本号
    @Inject
    @ConfigProperty(name = "app.database.url")
    private String dbUrl;
    public void printConfig() {
        System.out.println("版本: " + version);
        System.out.println("数据库: " + dbUrl);
    }
}

优雅停机 + 健康检查(生产必备)

场景:当应用部署到 Kubernetes 时,健康检查和生命周期管理非常重要。

// 健康检查接口(Helidon 自动提供 /health 端点)
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Liveness;
import javax.enterprise.context.ApplicationScoped;
@Liveness
@ApplicationScoped
public class SimpleHealthCheck implements HealthCheck {
    @Override
    public HealthCheckResponse call() {
        // 返回服务是存活的
        return HealthCheckResponse.named("memory-check")
                .up()
                .build();
    }
}

启动后访问:

  • http://localhost:8080/health —— 健康检查
  • http://localhost:8080/metrics —— 性能监控指标(需要依赖)

对比总结:SE vs MP 怎么选?

维度 Helidon SE Helidon MP
风格 函数式编程,类似 Node.js 的 Express 全注解,类似 Spring Boot 和 JAX-RS
性能 启动 < 100ms,内存仅 50MB 启动略慢,约 1-2 秒
依赖注入 手动管理(无 CDI) 完整支持 CDI(上下文依赖注入)
适合场景 高并发、极致性能、轻量级 IoT 企业级复杂业务、团队协作

最佳实践建议

  1. 如果只是做内部微服务:推荐 Helidon MP,因为开发效率高,团队容易上手。
  2. 如果是极端性能场景(比如响应式网关):推荐 Helidon SE,配合虚拟线程(JDK 21 虚拟线程支持非常好)能达到惊人的并发量。

案例覆盖了 REST、数据库、远程调用、配置和健康检查,你可以直接复制代码在本地运行,如果有具体场景(比如想对接 Kafka 或 Redis),可以告诉我,我给你补充对应代码。

抱歉,评论功能暂时关闭!