java呼叫kettle設定變數和引數
阿新 • • 發佈:2018-12-19
楔子
java呼叫kettle ,變數和引數的設定
java程式碼中變數會覆蓋kettle 裡面設定的變數
需要注意變數和引數 他倆是不一樣的
public class JobMail {
public static void main(String[] args) throws KettleException {
KettleDatabaseRepository repository = KettleUtils.kettleDbRepository;
String job_path = "/201811_JOB";
String job_name = "A_郵件job_para" ;
execJob(repository, job_path, job_name);
}
/**
* 執行 JOB
*
* @param repository
* kettle資料庫資源庫
* @param job_path
* JOB 目錄
* @param job_name
* JOB 名稱
* @throws KettleException
*/
private static void execJob(KettleDatabaseRepository repository, String job_path, String job_name) throws KettleException {
RepositoryDirectoryInterface dir = repository.findDirectory(job_path);
JobMeta jobMeta = repository.loadJob(repository.getJobId(job_name, dir), null);
Job job = new Job(repository, jobMeta);
// 設定引數
jobMeta.setParameterValue("sql_file" , "d://12");
jobMeta.setParameterValue("sql_file_para", "java中引數");
job.setLogLevel(LogLevel.DEBUG);
// 設定變數 java程式碼中變數會覆蓋kettle裡面設定的變數
job.setVariable("sql_file", "d://13");
// 啟動執行指定的job
job.start();
job.waitUntilFinished();// 等待job執行完;
job.setFinished(true);
System.out.println(job.getResult());
}
}
public class KettleUtils {
private static Logger logger = Logger.getLogger(KettleUtils.class);
private KettleUtils() throws Exception {
throw new Exception("工具類不允許建立");
}
/**
* kettle 資源庫
*/
public static KettleDatabaseRepository kettleDbRepository;
static {
if (kettleDbRepository == null) {
kettleDbRepository = getKettleDatabaseRepository();
logger.info("例項化kettle資源庫");
}
}
/**
* 設定kettle資源庫連線資訊
*
* @return
*/
public static DatabaseMeta setDatabaseMeta() {
return new DatabaseMeta(PropUtils.getConfigValByKey("name"), PropUtils.getConfigValByKey("type"), PropUtils.getConfigValByKey("access"), PropUtils.getConfigValByKey("host"), PropUtils.getConfigValByKey("db"), PropUtils.getConfigValByKey("port"), PropUtils.getConfigValByKey("user"), PropUtils.getConfigValByKey("pass"));
}
/**
* kettle 資源庫 獲取
*
* @return
*/
private static KettleDatabaseRepository getKettleDatabaseRepository() {
try {
KettleEnvironment.init();
// 建立DB資源庫
KettleDatabaseRepository repository = new KettleDatabaseRepository();
DatabaseMeta databaseMeta = KettleUtils.setDatabaseMeta();
// 選擇資源庫 此處參我與本地不一致還是正確執行
KettleDatabaseRepositoryMeta kettleDatabaseRepositoryMeta = new KettleDatabaseRepositoryMeta("Kettle", "Kettle", "Transformation description", databaseMeta);
repository.init(kettleDatabaseRepositoryMeta);
// 連線資源庫 DatabaseMeta中已經設定了,不明白此處為何還要再次設定
repository.connect("admin", "admin");
return repository;
} catch (KettleException e) {
e.printStackTrace();
logger.error("kettle資源庫連線失敗");
}
return null;
}
}