AbstractDataLoader.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.qingjian.module.dm.clean;
  2. import com.qingjian.common.base.Cleaned;
  3. import com.qingjian.common.constants.StrConsts;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.duckdb.DuckDBAppender;
  6. import org.duckdb.DuckDBConnection;
  7. import org.noear.solon.Solon;
  8. import org.noear.solon.data.dynamicds.DynamicDataSource;
  9. import org.noear.solon.data.dynamicds.DynamicDsKey;
  10. @Slf4j
  11. public abstract class AbstractDataLoader<S, T extends Cleaned> implements DataLoader<S, T> {
  12. protected DuckDBConnection duckDBConnection;
  13. protected DuckDBAppender duckDBAppender;
  14. private final String tableName;
  15. public AbstractDataLoader(String tableName) {
  16. this.tableName = tableName;
  17. try {
  18. DynamicDataSource ds = Solon.context().getBean("db1");
  19. DynamicDsKey.with(StrConsts.DS_KEY_CASE, () -> {
  20. duckDBConnection = (DuckDBConnection) ds.getConnection();
  21. duckDBAppender = duckDBConnection.createAppender(DuckDBConnection.DEFAULT_SCHEMA, tableName);
  22. });
  23. log.info("初始化 DuckDB 数据加载器成功, tableName={}", tableName);
  24. } catch (Exception e) {
  25. log.error("初始化 DuckDB 数据加载器失败, tableName={}", tableName, e);
  26. }
  27. }
  28. @Override
  29. public void write(S record) {
  30. if (record == null) {
  31. log.info("跳过空记录写入, tableName={}", tableName);
  32. return;
  33. }
  34. T t = convert(record);
  35. long l = System.currentTimeMillis();
  36. fillData(t);
  37. log.info("写入 fillData 成功, tableName={}, cost={}", tableName, System.currentTimeMillis() - l);
  38. //doWrite(t);
  39. }
  40. @Override
  41. public T convert(S source) {
  42. return (T) source;
  43. }
  44. protected abstract void doWrite(T record);
  45. @Override
  46. public void fillData(T record) {
  47. }
  48. @Override
  49. public void close() {
  50. // 倒序关闭,且单独捕获异常,避免一个资源关闭失败影响另一个
  51. if (duckDBAppender != null) {
  52. try {
  53. duckDBAppender.close();
  54. } catch (Exception e) {
  55. // 添加日志记录 Appender 关闭失败
  56. log.error("DuckDB Appender 关闭失败, tableName={}", tableName, e);
  57. }
  58. }
  59. if (duckDBConnection != null) {
  60. try {
  61. duckDBConnection.close();
  62. } catch (Exception e) {
  63. log.error("DuckDB 连接关闭失败, tableName={}", tableName, e);
  64. }
  65. }
  66. }
  67. }