在学习的时候我们一般都是针对单个库的增删改查,而在生产环境下,一般一个需求涉及到好几个不同数据的数据交互,所以就需要在代码中实现不同数据库的简单自由的切换。
为了在开发中以最简单的方法使用,我是基于注解和AOP的方法实现,在spring boot框架的项目中,添加本文实现的代码类后,只需要配置好数据源就可以直接通过注解使用,简单方便。以下讲解具体配置:
一配置二使用
①. 启动类注册动态数据源
②. 配置文件中配置多个数据源
③. 在需要的方法上使用注解指定数据源
1、在启动类添加 @Import({DynamicDataSourceRegister.class, MProxyTransactionManagementConfiguration.class})
[Java] 纯文本查看 复制代码 @SpringBootApplication
// 扫描mapper
@MapperScan(basePackages = "com.dao.mapper")
@Import({ DynamicDataSourceRegister.class })
@ComponentScan(basePackages = "com.dao")
public class CommServiceApplication {
public static void main(String [] args)
{
SpringApplication.run(CommServiceApplication.class,args);
}
2、配置文件配置内容为:
(不包括项目中的其他配置,这里只是数据源相关的)[Java] 纯文本查看 复制代码 ##zw_cash db
## read
jdbc.cashreadDataSource.dsType=com.alibaba.druid.pool.DruidDataSource
jdbc.cashreadDataSource.driverClassName=com.mysql.jdbc.Driver
jdbc.cashreadDataSource.url=jdbc:mysql://db.zcaifu.com:3307/zw_cash?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.cashreadDataSource.username=test
jdbc.cashreadDataSource.password=ioHuN3p*YgiaK%!V
## write
jdbc.cashWriteDataSource.dsType=com.alibaba.druid.pool.DruidDataSource
jdbc.cashWriteDataSource.driverClassName=com.mysql.jdbc.Driver
jdbc.cashWriteDataSource.url=jdbc:mysql://db.zcaifu.com:3307/zw_cash?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.cashWriteDataSource.username=test
jdbc.cashWriteDataSource.password=ioHuN3p*YgiaK%!V
#mgt_prod
jdbc.mgt_prodReadDataSource.dsType=com.alibaba.druid.pool.DruidDataSource
jdbc.mgt_prodReadDataSource.driverClassName=com.mysql.jdbc.Driver
jdbc.mgt_prodReadDataSource.url=jdbc:mysql://db.zcaifu.com:3307/mgt_prod?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.mgt_prodReadDataSource.username=test
jdbc.mgt_prodReadDataSource.password=ioHuN3p*YgiaK%!V
jdbc.mgt_prodWriteDataSource.dsType=com.alibaba.druid.pool.DruidDataSource
jdbc.mgt_prodWriteDataSource.driverClassName=com.mysql.jdbc.Driver
jdbc.mgt_prodWriteDataSource.url=jdbc:mysql://db.zcaifu.com:3307/mgt_prod?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.mgt_prodWriteDataSource.username=test
jdbc.mgt_prodWriteDataSource.password=ioHuN3p*YgiaK%!V
3、使用注解@TargetDataSource指定数据源
[Java] 纯文本查看 复制代码 @Mapper
public interface OrderMapper {
/**
* 通过订单状态查询到所有订单
* @return 所有订单列表
*/
@TargetDataSource(DataSourceKey.BIZ_READ_DATASOURCE_KEY)
List<Order> getOrderListByState(int state);}
4.自定义注解,也可以直接将以下几个类放到项目中
[Java] 纯文本查看 复制代码 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
[Java] 纯文本查看 复制代码 /**
* 切换数据源Advice
*/
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
@Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
String dsId = ds.name();
if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature());
} else {
logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
DynamicDataSourceContextHolder.setDataSourceType(ds.name());
}
}
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
[Java] 纯文本查看 复制代码 public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static List<String> dataSourceIds = new ArrayList<>();
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
return contextHolder.get();
}
public static void clearDataSourceType() {
contextHolder.remove();
}
/**
* 判断指定DataSrouce当前是否存在
* @param dataSourceId
*/
public static boolean containsDataSource(String dataSourceId){
return dataSourceIds.contains(dataSourceId);
}
}
[Java] 纯文本查看 复制代码 /**
* 动态数据源注册
*/
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private Logger logger = Logger.getLogger(DynamicDataSourceRegister.class);
// 默认数据源
private DataSource defaultDataSource;
// 动态数据源
private Map<String, DataSource> dynamicDataSources = new HashMap<String, DataSource>();
// 数据源配置信息
private PropertyValues dataSourcePropertyValues;
@Override
public void setEnvironment(Environment env) {
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
String dsPrefixs = propertyResolver.getProperty("datasources");
try {
for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
Map<String, Object> map = propertyResolver.getSubProperties(dsPrefix + ".");
DataSource ds = initDataSource(map);
//设置默认数据源
if ("cashreadDataSource".equals(dsPrefix)) {
// logger.info("======"+dsPrefix+"==========");
defaultDataSource = ds;
} else {
dynamicDataSources.put(dsPrefix, ds);
// logger.info("======"+dsPrefix+"==========");
}
dataBinder(ds, env);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 初始化数据源
*
* @param map
* @return
*/
@SuppressWarnings("unchecked")
public DataSource initDataSource(Map<String, Object> map) {
DataSource dataSource = null;
try {
String driverClassName = map.get("driverClassName").toString();
String url = map.get("url").toString();
String username = map.get("username").toString();
String password = map.get("password").toString();
String dsType = map.get("dsType").toString();
Class<DataSource> dataSourceType;
dataSourceType = (Class<DataSource>) Class.forName(dsType);
dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username)
.password(password).type(dataSourceType).build();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dataSource;
}
/**
* 加载数据源配置信息
*
* @param dataSource
* @param env
*/
private void dataBinder(DataSource dataSource, Environment env) {
RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
dataBinder.setIgnoreNestedProperties(false);// false
dataBinder.setIgnoreInvalidFields(false);// false
dataBinder.setIgnoreUnknownFields(true);// true
if (dataSourcePropertyValues == null) {
Map<String, Object> values = new RelaxedPropertyResolver(env, "datasource").getSubProperties(".");
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
}
/**
* 注册数据源been
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 将主数据源添加到更多数据源中
targetDataSources.put("dataSource", defaultDataSource);
// 添加更多数据源
targetDataSources.putAll(dynamicDataSources);
// 创建DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition);
}
}
[Java] 纯文本查看 复制代码 /**
* 在方法上使用,用于指定使用哪个数据源
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String value();
}
|