You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.dsideal.FengHuang.Plugin;
import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.jfinal.plugin.druid.DruidPlugin;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 读写分离扩展类
*/
public class SlaveDrudPlugin implements IPlugin, IDataSourceProvider {
//读写分离的rule
MasterSlaveRuleConfiguration masterSlaveRuleConfiguration;
//数据源map
Map<String, DruidPlugin> druidPlugins;
//原数据库连接源map
Map<String, DataSource> dataSourceMap;
//最终sharding-jdbc封装后的数据库连接源
DataSource dataSource;
public SlaveDrudPlugin(MasterSlaveRuleConfiguration masterSlaveRuleConfiguration, Map<String, DruidPlugin> druidPlugins) {
this.masterSlaveRuleConfiguration = masterSlaveRuleConfiguration;
this.druidPlugins = druidPlugins;
dataSourceMap = new HashMap<>();
}
public boolean start() {
//遍历数据源 将数据源加入sharding jdbc
for (Map.Entry<String, DruidPlugin> entry : druidPlugins.entrySet()) {
entry.getValue().start();
dataSourceMap.put(entry.getKey(), entry.getValue().getDataSource());
}
try {
dataSource =
MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfiguration,
new Properties());
System.out.println(dataSource);
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
public boolean stop() {
for (Map.Entry<String, DruidPlugin> entry : druidPlugins.entrySet()) {
entry.getValue().stop();
dataSourceMap.put(entry.getKey(), entry.getValue().getDataSource());
}
return true;
}
public DataSource getDataSource() {
return dataSource;
}
}