springbootr如何调用dolphinshceduler

在 Spring Boot 中调用 DolphinScheduler 的接口主要分为两种方式:

  1. 直接调用其 RESTful API(推荐,最常用)
  2. 使用官方提供的 Java API Client(本质是对 REST API 的封装)

下面我将详细讲解这两种方式,并提供代码示例。

方式一:直接调用 RESTful API(推荐)

这是最通用、最灵活的方式。DolphinScheduler 的所有前端操作最终都指向其后端 API,我们只需要在 Spring Boot 中使用 RestTemplateWebClient 来模拟 HTTP 请求即可。

步骤 1:添加依赖

确保pom.xml 中包含 Web 依赖。

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
步骤 2:编写调用代码

这里以使用 RestTemplate 为例。

a. 配置 RestTemplate 和 API 基础信息

可以在 application.yml 中配置 Dolphinscheduler 服务器的地址和凭证。

复制代码
dolphinscheduler:
  api:
    base-url: http://your-dolphinscheduler-server:12345/dolphinscheduler
    username: admin
    password: admin

b. 编写一个工具类(DolphinSchedulerService)来处理登录和请求

复制代码
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Service
public class DolphinSchedulerService {

    private final String baseUrl;
    private final String username;
    private final String password;
    private final RestTemplate restTemplate;
    private String sessionId; // 存储登录后的 session

    public DolphinSchedulerService(@Value("${dolphinscheduler.api.base-url}") String baseUrl,
                                   @Value("${dolphinscheduler.api.username}") String username,
                                   @Value("${dolphinscheduler.api.password}") String password,
                                   RestTemplate restTemplate) {
        this.baseUrl = baseUrl;
        this.username = username;
        this.password = password;
        this.restTemplate = restTemplate;
    }

    /**
     * 项目启动后自动登录,获取 Session
     */
    @PostConstruct
    public void login() {
        String url = baseUrl + "/login";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 设置请求体
        Map<String, String> loginRequest = new HashMap<>();
        loginRequest.put("userName", username);
        loginRequest.put("userPassword", password);

        HttpEntity<Map<String, String>> request = new HttpEntity<>(loginRequest, headers);

        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> data = (Map<String, Object>) response.getBody().get("data");
                this.sessionId = (String) data.get("sessionId");
                System.out.println("Login successful! Session ID: " + sessionId);
            } else {
                throw new RuntimeException("Login failed: " + response.getBody());
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to login to DolphinScheduler", e);
        }
    }

    /**
     * 创建一个通用的 GET 请求方法,自动携带 Session
     */
    public <T> T get(String apiPath, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("sessionId", sessionId); // DolphinScheduler API 通过 sessionId 鉴权
        HttpEntity<String> entity = new HttpEntity<>(headers);

        String url = baseUrl + apiPath;
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, entity, responseType);
        return response.getBody();
    }

    /**
     * 创建一个通用的 POST 请求方法,自动携带 Session
     */
    public <T> T post(String apiPath, Object requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("sessionId", sessionId);
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);

        String url = baseUrl + apiPath;
        return restTemplate.postForObject(url, entity, responseType);
    }

    // 可以类似地实现 PUT、DELETE 等方法
}

c. 在 Controller 或 Business Service 中调用具体 API

现在你可以在任何需要的地方注入 DolphinSchedulerService,并调用 Dolphinscheduler 的功能。

示例 1:查询项目列表

复制代码
@RestController
@RequestMapping("/api/ds")
public class TestController {

    @Autowired
    private DolphinSchedulerService dsService;

    @GetMapping("/projects")
    public Object getProjects() {
        // API 路径可以从官方文档找到:/projects/list
        return dsService.get("/projects/list", Object.class);
    }
}

示例 2:启动一个工作流实例

复制代码
@Service
public class MyBusinessService {

    @Autowired
    private DolphinSchedulerService dsService;

    public void runWorkflow(Long projectCode, Long workflowCode) {
        String apiPath = "/projects/" + projectCode + "/executors/start-process-instance";
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("processDefinitionCode", workflowCode);
        // 其他可选参数,如失败策略、优先级、告警组等...
        // requestBody.put("failureStrategy", "CONTINUE");
        // requestBody.put("startNodeList", "node1,node2");
        
        Object response = dsService.post(apiPath, requestBody, Object.class);
        // 处理响应...
        System.out.println("Workflow started: " + response);
    }
}

方式二:使用官方 Java API Client

DolphinScheduler 提供了一个 dolphinscheduler-java-client 模块,它对 REST API 进行了封装。

步骤 1:添加客户端依赖

需要手动找到对应版本的客户端 JAR 包,或者从源码编译。注意:这个客户端可能不是官方主力维护的,使用时需要注意版本兼容性。

如果找不到,方式一更为稳妥。

步骤 2:使用客户端
复制代码
import org.apache.dolphinscheduler.api.DolphinSchedulerClient;
import org.apache.dolphinscheduler.api.DolphinSchedulerClientFactory;
import org.apache.dolphinscheduler.api.request.ProcessStartRequest;
import org.apache.dolphinscheduler.api.response.ProcessStartResponse;

// ... 

public void runWorkflowWithClient() {
    // 1. 创建客户端
    DolphinSchedulerClient client = DolphinSchedulerClientFactory.createClient(
        "http://your-dolphinscheduler-server:12345",
        "admin",
        "admin"
    );

    // 2. 构建请求
    ProcessStartRequest request = new ProcessStartRequest();
    request.setProjectName("my-project"); // 通常用名称或Code标识
    request.setProcessDefinitionName("my-workflow");
    // ... 设置其他参数

    try {
        // 3. 执行调用
        ProcessStartResponse response = client.startProcess(request);
        System.out.println("Process instance ID: " + response.getProcessInstanceId());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

重要注意事项

  1. API 文档 :所有可调用的接口及其参数,请务必查阅对应版本的 DolphinScheduler 官方 REST API 文档 。通常部署好后,访问 http://your-dolphinscheduler-server:12345/dolphinscheduler/doc.html 即可看到 Swagger 文档界面。这是最准确的参考。
  2. 认证(Authentication) :上述示例使用的是 Session 认证(登录后获取 sessionId 并放在 Header 中)。新版本的 DolphinScheduler 也支持 Token 认证,更适用于无状态交互。可以在安全中心生成 Token,然后直接在请求头中添加 "token: YOUR_TOKEN",无需登录步骤。
  3. 错误处理 :在实际生产中,务必为每个远程调用添加完善的错误处理(try-catch)、日志记录和重试机制。
  4. 异步操作:启动工作流等操作是异步的,API 调用成功只代表提交成功,不代表工作流执行成功。需要通过查询执行实例的接口来跟踪最终状态。
  5. 参数传递 :在启动工作流时,可以通过 execTypestartParams 等参数向下游任务传递自定义参数,这在动态控制流程行为时非常有用。

总结

对于大多数 Spring Boot 项目,首选方式一(直接调用 REST API) 。它简单、直接、不受特定客户端库版本和维护状态的限制,并且对整个过程有完全的控制力。只需要一个 HTTP 客户端(如 RestTemplateWebClient)和官方 API 文档即可开始集成。

相关推荐
zhz521435 分钟前
从PostgreSQL到人大金仓(KingBase)数据库迁移实战:Spring Boot项目完整迁移指南
数据库·spring boot·postgresql
用户0866554284813 小时前
记一次nacos配置文件解密插件不生效的问题
spring boot·spring cloud
叫我阿柒啊3 小时前
Java全栈开发面试实战:从基础到复杂场景的深度解析
java·数据库·spring boot·面试·vue·测试·全栈开发
3Cloudream3 小时前
互联网大厂Java面试实录:Spring Boot与微服务架构解析
spring boot·微服务·hibernate·jwt·java面试
风象南4 小时前
SpringBoot 程序 CPU 飙升排查:自制「方法级采样火焰图」
spring boot·后端
用户6120414922134 小时前
springboot+vue3做的图书管理与借阅系统
vue.js·spring boot·后端
仙俊红10 小时前
Spring Boot `@Configuration` 与 `@Component` 笔记
java·spring boot·笔记
计算机学姐13 小时前
基于SpringBoot的社团管理系统【2026最新】
java·vue.js·spring boot·后端·mysql·spring·mybatis
CodeLongBear14 小时前
Spring Boot 与 Spring MVC 的区别与联系:从本质到实践
spring boot·spring·mvc