代码示例

更新时间:2017-06-07 13:26:11

以一个用户利用CDP Java SDK完成创建Pipeline、提交Job、最后将其Kill为例,展示SDK详情(该Demo在CDP JAVA SDK中也有附带)

package com.alibaba.cdp.sdk.example;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.alibaba.cdp.sdk.model.Job;
import com.alibaba.cdp.sdk.model.JobStatus;
import com.alibaba.cdp.sdk.model.Pipeline;
import com.alibaba.cdp.sdk.model.Session;
/**
 * 样例编码,注意这个样例由于缺乏关键的作业信息实际不能运行!
 * 但是它能很好体现如何使用CDP SDK完成我们所需要的业务逻辑
 * */
public class JobExample {
    public static void main(String[] args) {
        // 登录
        Session session = new Session("http://cdp.aliyun.com/api",
                "your_accessId", "your_accessKey");
        // 如果没有project则创建
        Pipeline pipeline = new Pipeline();
        pipeline.setName("your_project_name");
        pipeline.setDescription("your_project_info");
        pipeline = session.createPipeline(pipeline);
        // 如果已有project,直接使用即可
//        Project project = session.getPipeline("your_project_name");
        // 提交Job
        Job job = new Job();
        job.setTraceId("your job trace info"); // 自定义用以追踪作业的信息
        job.setContext("your_job_json"); // 详情参看不同的同步方式配置信息
        final Job starter = pipeline.start(job);
        // 启动另外一个线程轮询打印状态
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(new Runnable() {
            @Override
            public void run() {
                JobStatus status;
                do {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    status = starter.status();
                    System.out.println(status);
                } while (status.isJobAlive());
            }
        });
        service.shutdown();
        // 等待job运行完成
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        // 如果没有完成,主线程Kill这个运行实例
        do {
            try {
                starter.stop();
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } while (starter.status().isJobAlive());
    }
}