org.zodiac.datasource.DynamicDataSourceProxy Maven / Gradle / Ivy
The newest version!
package org.zodiac.datasource;
//import lombok.SneakyThrows;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zodiac.datasource.config.DatabaseType;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 动态数据源代理,将数据源代理为动态数据源。
*/
public class DynamicDataSourceProxy implements DynamicDataSourceObject {
private final Logger log = LoggerFactory.getLogger(getClass());
private String id;
private volatile DatabaseType databaseType;
private DataSource proxy;
private final Lock lock = new ReentrantLock();
public DynamicDataSourceProxy(String id, DatabaseType databaseType, DataSource proxy) {
this.id = id;
this.databaseType = databaseType;
this.proxy = proxy;
}
public DynamicDataSourceProxy(String id, DataSource proxy) {
this.id = id;
this.proxy = proxy;
}
@Override
public DataSource getNative() {
return proxy;
}
@Override
public String getId() {
return id;
}
@Override
// @SneakyThrows
public DatabaseType getType() {
if (databaseType == null) {
lock.lock();
try {
if (databaseType != null) {
return databaseType;
}
try (Connection connection = proxy.getConnection()) {
databaseType = DatabaseType.fromJdbcUrl(connection.getMetaData().getURL());
} catch (SQLException e) {
log.error("SQL error {} with code [{}] and state [{}] .", e.getMessage(), e.getErrorCode(), e.getSQLState());
e.printStackTrace();
}
} finally {
lock.unlock();
}
}
return databaseType;
}
public DynamicDataSourceProxy setDatabaseType(DatabaseType databaseType) {
this.databaseType = databaseType;
return this;
}
}