记录一个自定义Driver(SPL集算器)

发布时间 2023-08-25 10:15:02作者: XSWClevo

实现:

  1. 覆盖官方的InternalDriver
  2. 实现Driver接口,实现自己的一套Driver
  3. 注册到Driver中

代码如下:
只贴上核心代码:
自定义数据源:

// 自定义数据源:
@Configuration
public class MyDataourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spl")
    public DataSource myDataSource(MyDriverProperties myDriverProperties) {
        InternalDriver internalDriver = new InternalDriver();
        // 删除官方的驱动
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            if (driver instanceof InternalDriver) {
                DriverManager.deregisterDriver(driver);
            }
        }
        RaqSoftConfig raqSoftConfig = new MyDataourceConfig();
        BeanUtils.copyProperties(myDriverProperties, raqSoftConfig);
        MyDriver driver = new MyDriver(internalDriver, raqSoftConfig);
        DriverManager.registerDriver(driver);
        return DataSourceBuilder.create().build();
    }

    @Bean
    public PlatformTransactionManager myPlatformTransactionManager(DataSource myDriverProperties) {
        return new DataSourceTransactionManager(myDriverProperties);
    }
}

自定义Driver

public class MyDriver implements Driver {

    private InternalDriver internalDriver;

    private RaqSoftConfig raqSoftConfig;

    public MyDriver() {
        this.internalDriver = new InternalDriver();
    }

    @Override
    public Connection connect(String url, Properties info) throws SQLException {
        // 自己从yml定义的属性,可以通过@ConfigurationProperties(prefix = "xxx.xxx")指定
        MyDriverProperties myDriverProperties = SpringContextUtils.getBean(MyDriverProperties.class);
        // 官方的默认配置类,从xml里面加载的配置
        RaqSoftConfig raqSoftConfig = new RaqSoftConfig();
        BeanUtils.copyProperties(myDriverProperties, raqSoftConfig);
        // 通过这里直接覆盖Spl官方的connect方法。达到我们的目的
        return internalDriver.connect(url, info, raqSoftConfig);
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return internalDriver.acceptsURL(url);
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
        return internalDriver.getPropertyInfo(url, info);
    }
    .......

自定义配置文件,与官方配置文件对应

@ConfigurationProperties(prefix = "spl")
public class MyDriverProperties {
}


/*
对应的yml配置属性如下:
spl:
   defDataSource: xxxx  # 默认数据源
   dbList:
     - name: mysql
       url: jdbc....
       driver: com.xxxDriver
       dbType: 0
       user: ...
       password: ...
       ....
     - name: clickhouse
       url: ..
       ...
   autoConnectList:
     - mysql
     - clickhouse
     - ...
 */

最后的使用只需要将DataSource注入的代码中即可
随意举个例子:
@AutoWrite
@Qua...(value = "myDataSource")
DataSource dataSource;
或者构造器注入