use of io.shardingjdbc.core.jdbc.core.datasource.NamedDataSource in project sharding-jdbc by shardingjdbc.
the class ShardingConnection method getConnection.
/**
* Get database connection via data source name.
*
* @param dataSourceName data source name
* @param sqlType SQL type
* @return all database connections via data source name
* @throws SQLException SQL exception
*/
public Connection getConnection(final String dataSourceName, final SQLType sqlType) throws SQLException {
if (getCachedConnections().containsKey(dataSourceName)) {
return getCachedConnections().get(dataSourceName);
}
DataSource dataSource = shardingContext.getDataSourceMap().get(dataSourceName);
Preconditions.checkState(null != dataSource, "Missing the rule of %s in DataSourceRule", dataSourceName);
String realDataSourceName;
if (dataSource instanceof MasterSlaveDataSource) {
NamedDataSource namedDataSource = ((MasterSlaveDataSource) dataSource).getDataSource(sqlType);
realDataSourceName = namedDataSource.getName();
if (getCachedConnections().containsKey(realDataSourceName)) {
return getCachedConnections().get(realDataSourceName);
}
dataSource = namedDataSource.getDataSource();
} else {
realDataSourceName = dataSourceName;
}
Connection result = dataSource.getConnection();
getCachedConnections().put(realDataSourceName, result);
replayMethodsInvocation(result);
return result;
}
use of io.shardingjdbc.core.jdbc.core.datasource.NamedDataSource in project sharding-jdbc by shardingjdbc.
the class DataSourceGsonTypeAdapter method read.
@SuppressWarnings("unchecked")
@Override
public NamedDataSource read(final JsonReader in) throws IOException {
String name = "";
String clazz = "";
Map<String, Object> properties = new TreeMap<>();
in.beginObject();
while (in.hasNext()) {
String jsonName = in.nextName();
switch(jsonName) {
case DataSourceGsonTypeConstants.DATASOURCE_NAME:
name = in.nextString();
break;
case DataSourceGsonTypeConstants.CLAZZ_NAME:
clazz = in.nextString();
break;
default:
properties.put(jsonName, in.nextString());
break;
}
}
in.endObject();
try {
return new NamedDataSource(name, DataSourceUtil.getDataSource(clazz, properties));
} catch (final ReflectiveOperationException ex) {
throw new ShardingJdbcException(ex);
}
}
use of io.shardingjdbc.core.jdbc.core.datasource.NamedDataSource in project sharding-jdbc by shardingjdbc.
the class DataSourceJsonConverter method fromJson.
/**
* Convert data source map from json.
*
* @param json data source map json string
* @return data source map
*/
@SuppressWarnings("unchecked")
public static Map<String, DataSource> fromJson(final String json) {
Map<String, DataSource> result = new LinkedHashMap<>();
List<NamedDataSource> namedDataSources = GsonFactory.getGson().fromJson(json, new TypeToken<List<NamedDataSource>>() {
}.getType());
for (NamedDataSource each : namedDataSources) {
result.put(each.getName(), each.getDataSource());
}
return result;
}
Aggregations