手把手教你使用Kettle JAVA API進行數據抽取

Kettle作爲一款優秀的數據抽取程序,因爲高效穩定的性能,一直被廣大使用者所喜愛,並且還在國內廣受好評。因爲其本身使用純JAVA編寫,所以其JAVA API使用起來自然也是非常簡便。雖然其本身自帶的組件已經非常好用,並且能夠滿足豐富的場景。但可能有些場景下,我們可能需要通過其他的方式來實現,本篇我們將介紹Kettle的JAVA API的使用。

一、環境搭建

Pentaho官方倉庫:https://nexus.pentaho.org/content/groups/omni

核心jar包的pom.xml配置如下:

  1. <dependency>
  2. <groupId>pentaho-kettle</groupId>
  3. <artifactId>kettle-engine</artifactId>
  4. <version>4.4.0-stable</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>pentaho-kettle</groupId>
  8. <artifactId>kettle-core</artifactId>
  9. <version>4.4.0-stable</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>pentaho-kettle</groupId>
  13. <artifactId>kettle-db</artifactId>
  14. <version>4.4.0-stable</version>
  15. </dependency>

 

二、代碼部分

1、初始化環境

  1. public void initKettleEnvironment(HttpServletRequest request) throws KettleException {
  2. if (KettleEnvironment.isInitialized()) {
  3. return;
  4. }
  5. /**
  6. * 爲避免在部分網絡環境中無法完成初始化,需要自行處理
  7. */
  8. if (request == null) {
  9. // 運行環境初始化
  10. KettleEnvironment.init();
  11. } else {
  12. String userDir = System.getProperty("user.dir");
  13. String kettleHome = request.getSession().getServletContext().getRealPath(File.separator "WEB-INF");
  14. // 設置用戶路徑和系統環境,包括用戶路徑和主目錄
  15. System.setProperty("user.dir", kettleHome);
  16. System.setProperty("KETTLE_HOME", kettleHome);
  17. // 運行環境初始化
  18. KettleEnvironment.init();
  19. // 避免造成影響其他程序的運行,還原用戶路徑
  20. System.setProperty("user.dir", userDir);
  21. }
  22. }

2、創建轉化元

添加配置數組,配置轉化元

  1. public TransMeta buildTransMeta(String metaName, String... transXML) throws KettleXMLException {
  2. TransMeta transMeta = new TransMeta();
  3. // 設置轉化元的名稱
  4. transMeta.setName(metaName);
  5. // 添加轉換的數據庫連接
  6. for (int i = 0; i < transXML.length; i ) {
  7. transMeta.addDatabase(new DatabaseMeta(transXML[i]));
  8. }
  9. return transMeta;
  10. }

3、添加日誌(可選操作)

  1. public void setStepLogTable(TransMeta transMeta, String connDbName, String tableName) {
  2. VariableSpace space = new Variables();
  3. // 將step日誌數據庫配置名加入到變量集中
  4. space.setVariable(Const.KETTLE_TRANS_LOG_DB, connDbName);
  5. space.initializeVariablesFrom(null);
  6. StepLogTable stepLogTable = StepLogTable.getDefault(space, transMeta);
  7. // 配置StepLogTable使用的數據庫配置名稱
  8. stepLogTable.setConnectionName(connDbName);
  9. // 設置Step日誌的表名
  10. stepLogTable.setTableName(tableName);
  11. // 設置TransMeta的StepLogTable
  12. transMeta.setStepLogTable(stepLogTable);
  13. }

4、創建插件註冊器

  1. public PluginRegistry getRegistry() {
  2. // 插件註冊,用於註冊轉換中需要用到的插件
  3. return PluginRegistry.getInstance();
  4. }

5、設置表輸入步驟元

該步驟用於獲取源數據

  1. /**
  2. * 設置表輸入步驟
  3. * @param transMeta
  4. * @param registry
  5. * @param sourceDbName
  6. * @param sql
  7. * @param stepName
  8. * @return
  9. */
  10. public StepMeta setTableInputStep(TransMeta transMeta, PluginRegistry registry, String sourceDbName, String sql,
  11. String stepName) {
  12. // 創建表輸入
  13. TableInputMeta tableInputMeta = new TableInputMeta();
  14. String pluginId = registry.getPluginId(StepPluginType.class, tableInputMeta);
  15. // 指定數據源數據庫配置名
  16. DatabaseMeta source = transMeta.findDatabase(sourceDbName);
  17. tableInputMeta.setDatabaseMeta(source);
  18. tableInputMeta.setSQL(sql);
  19. // 將表輸入添加到轉換中
  20. StepMeta stepMeta = new StepMeta(pluginId, stepName, tableInputMeta);
  21. // 給步驟添加在spoon工具中的顯示位置
  22. stepMeta.setDraw(true);
  23. stepMeta.setLocation(100, 100);
  24. // 將表輸入添加到步驟中
  25. transMeta.addStep(stepMeta);
  26. return stepMeta;
  27. }

6、更新步驟元

該步驟用於將獲取到的數據更新到目標數據庫中

  1. /**
  2. * 設置表輸出步驟,用於整表抽取
  3. * @param transMeta
  4. * @param registry
  5. * @param targetDbName
  6. * @param targetTableName
  7. * @param stepName
  8. * @return
  9. */
  10. public StepMeta setTableOutput(TransMeta transMeta, PluginRegistry registry, String targetDbName,
  11. String targetTableName, String stepName) {
  12. // 創建表輸出
  13. TableOutputMeta tableOutputMeta = new TableOutputMeta();
  14. String pluginId = registry.getPluginId(StepPluginType.class, tableOutputMeta);
  15. // 配置表輸出的目標數據庫配置名
  16. DatabaseMeta targetDb = transMeta.findDatabase(targetDbName);
  17. tableOutputMeta.setDatabaseMeta(targetDb);
  18. tableOutputMeta.setTableName(targetTableName);
  19. // 將表輸出添加到轉換中
  20. StepMeta stepMeta = new StepMeta(pluginId, stepName, tableOutputMeta);
  21. transMeta.addStep(stepMeta);
  22. return stepMeta;
  23. }
  24. /**
  25. * 設置表插入與更新步驟,用於表中部分字段更新
  26. * @param transMeta
  27. * @param registry
  28. * @param targetDbName
  29. * @param targetTableName
  30. * @param updatelookup lookup檢索字段
  31. * @param updateStream lookup更新字段
  32. * @param updateStream2 lookup更新字段2
  33. * @param conditions lookup條件
  34. * @param updateOrNot lookup更新標記
  35. * @param stepName
  36. * @return
  37. */
  38. public StepMeta setInsertUpdateMeta(TransMeta transMeta, PluginRegistry registry, String targetDbName,
  39. String targetTableName, String[] updatelookup, String[] updateStream, String[] updateStream2,
  40. String[] conditions, Boolean[] updateOrNot, String stepName) {
  41. // 創建插入與更新
  42. InsertUpdateMeta insertUpdateMeta = new InsertUpdateMeta();
  43. String pluginId = registry.getPluginId(StepPluginType.class, insertUpdateMeta);
  44. // 配置目標數據庫配置名
  45. DatabaseMeta database_target = transMeta.findDatabase(targetDbName);
  46. insertUpdateMeta.setDatabaseMeta(database_target);
  47. // 設置目標表名
  48. insertUpdateMeta.setTableName(targetTableName);
  49. // 設置用來查詢的關鍵字
  50. insertUpdateMeta.setKeyLookup(updatelookup);
  51. insertUpdateMeta.setKeyStream(updateStream);
  52. insertUpdateMeta.setKeyStream2(updateStream2);// 這一步不能省略
  53. insertUpdateMeta.setKeyCondition(conditions);
  54. // 設置要更新的字段
  55. insertUpdateMeta.setUpdateLookup(updatelookup);
  56. insertUpdateMeta.setUpdateStream(updateStream);
  57. insertUpdateMeta.setUpdate(updateOrNot);
  58. // 添加步驟到轉換中
  59. StepMeta stepMeta = new StepMeta(pluginId, stepName, insertUpdateMeta);
  60. stepMeta.setDraw(true);
  61. stepMeta.setLocation(250, 100);
  62. transMeta.addStep(stepMeta);
  63. return stepMeta;
  64. }

7、綁定關聯步驟

該步驟用於將數據獲取和導入更新的步驟關聯綁定

  1. /**
  2. * 用於將表輸入步驟與第二步驟綁定
  3. * @param transMeta
  4. * @param from
  5. * @param to
  6. */
  7. public void addTransHop(TransMeta transMeta, StepMeta from, StepMeta to) {
  8. transMeta.addTransHop(new TransHopMeta(from, to));
  9. }

8、執行抽取

執行數據抽取

  1. /**
  2. * 執行抽取
  3. * @param transMeta
  4. * @param targetDbName
  5. */
  6. public void executeTrans(TransMeta transMeta, String targetDbName) {
  7. try {
  8. Database database = new Database(null, transMeta.findDatabase(targetDbName));
  9. database.connect();
  10. Trans trans = new Trans(transMeta);
  11. trans.execute(new String[] { "start..." });
  12. trans.waitUntilFinished();
  13. // 關閉數據庫連接
  14. database.disconnect();
  15. if (trans.getErrors() > 0) {
  16. throw new RuntimeException("There were errors during transformation execution.");
  17. }
  18. } catch (KettleDatabaseException e) {
  19. e.printStackTrace();
  20. } catch (KettleException e) {
  21. e.printStackTrace();
  22. }
  23. }

9、抽取示例

數據庫配置xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <connection>
  3.     <name>smy</name>
  4.     <server>127.0.0.1</server>
  5.     <type>Mysql</type>
  6.     <access>Native</access>
  7.     <database>test_db</database>
  8.     <port>3306</port>
  9.     <username>root</username>
  10.     <password>123456</password>
  11.     <attributes>
  12.         <attribute>
  13.             <code>USE_POOLING</code>
  14.             <attribute>Y</attribute>
  15.         </attribute>
  16.         <attribute>
  17.             <code>EXTRA_OPTION_MYSQL.characterEncoding</code>
  18.             <attribute>utf8</attribute>
  19.         </attribute>
  20.         <attribute>
  21.             <code>EXTRA_OPTION_MYSQL.defaultFetchSize</code>
  22.             <attribute>500</attribute>
  23.         </attribute>
  24.     </attributes>
  25. </connection> 

運行函數:

  1. public static void main(String[] args) {
  2. try {
  3. KettleClient client = new KettleClient();
  4. client.initEnvironment(null);
  5. String transXML = ""; // 此處爲上例的數據庫配置
  6. TransMeta meta = client.buildTransMeta("kettle", transXML);
  7. PluginRegistry registry = client.getRegistry();
  8. StepMeta step1 = client.setTableInputStep(meta, registry, "kettle", "select * from test1", "table input");
  9. StepMeta step2 = client.setTableOutput(meta, registry, "kettle", "test2", "table insert");
  10. client.addTransHop(meta, step1, step2);
  11. client.executeTrans(meta, "kettle");
  12. } catch (KettleException e) {
  13. e.printStackTrace();
  14. }
  15. }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章