com.dexcoder.dal.spring.datasource.DynamicDataSourceUtils Maven / Gradle / Ivy
package com.dexcoder.dal.spring.datasource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import com.dexcoder.commons.utils.ClassUtils;
import com.dexcoder.commons.utils.PropertyUtils;
import com.dexcoder.commons.utils.StrUtils;
import com.dexcoder.dal.exceptions.JdbcAssistantException;
/**
* Created by liyd on 2015-10-30.
*/
public class DynamicDataSourceUtils {
/**
* 设置数据源权重量
*
* @param readDsList the read ds list
* @param writeDsList the write ds list
* @param dsId the ds id
* @param weight the weight
*/
public static void addWeightDataSource(List readDsList, List writeDsList, String dsId, int weight,
String mode) {
if (StrUtils.equalsIgnoreCase(mode, DynamicDataSource.DS_MODE_R)) {
for (int i = 0; i < weight; i++) {
readDsList.add(dsId);
}
} else if (StrUtils.equalsIgnoreCase(mode, DynamicDataSource.DS_MODE_W)) {
for (int i = 0; i < weight; i++) {
writeDsList.add(dsId);
}
} else if (StrUtils.equalsIgnoreCase(mode, DynamicDataSource.DS_MODE_RW)) {
for (int i = 0; i < weight; i++) {
readDsList.add(dsId);
writeDsList.add(dsId);
}
} else {
throw new JdbcAssistantException("动态数据源读写模式设置错误,应为其中一种:[mode=r,mode=w,mode=rw]");
}
}
/**
* 设置数据源各项属性
*
* @param map
* @param dataSource
*/
public static void setDsProperties(Map map, DataSource dataSource) {
Set> entries = map.entrySet();
for (Map.Entry entry : entries) {
String name = entry.getKey();
PropertyDescriptor propertyDescriptor = ClassUtils.getPropertyDescriptor(dataSource.getClass(), name);
if (propertyDescriptor == null || propertyDescriptor.getWriteMethod() == null) {
continue;
}
Method writeMethod = propertyDescriptor.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
Object value = ClassUtils.toTargetTypeValue(entry.getValue(), propertyDescriptor.getPropertyType());
ClassUtils.invokeMethod(writeMethod, dataSource, value);
}
}
/**
* 获取并移除元素
*
* @param map
* @return
*/
public static String getAndRemoveValue(Map map, String key, String defaultValue) {
String value = map.get(key);
map.remove(key);
if (StrUtils.isBlank(value) && StrUtils.isBlank(defaultValue)) {
throw new JdbcAssistantException("属性不能为空:" + key);
}
return StrUtils.isBlank(value) ? defaultValue : value;
}
/**
* 解析数据源信息
*
* @param dsConfigFile
* @return
*/
public static List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy