io.shardingsphere
sharding-jdbc-spring-boot-starter
3.0.0
public class DatabaseContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
public static void setDatabaseType(String databaseType){
contextHolder.set(databaseType);
}
public static String getDatabaseType(){
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getDatabaseType();
}
}
public enum DatabaseType {
SHARDING_DATA_SOURCE("shardingDataSource","sharding-jdbc数据源"),
DRUID_DATA_SOURCE("druidDataSource","druid数据源");
private String source;
private String desc;
DatabaseType(String source,String desc){
this.source=source;
this.desc=desc;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UseDataSource {
DatabaseType source();
}
@Component
@Aspect
@Order(Ordered.LOWEST_PRECEDENCE-1)
public class UseDataSourceAspect {
@Pointcut("@annotation(UseDataSource)")
public void useDataSource() {
}
@Around("useDataSource() && @annotation(anno)")
public Object dataSourceSwitcher(ProceedingJoinPoint joinPoint, UseDataSource anno) throws Throwable {
DatabaseContextHolder.setDatabaseType(anno.source().getSource());
try {
//执行方法
Object result = joinPoint.proceed();
return result;
}catch (Exception e){
throw e;
}finally {
//切换回原来的数据源(重要)
DatabaseContextHolder.clearDataSource();
}
}
}
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import io.shardingsphere.api.config.ShardingRuleConfiguration;
import io.shardingsphere.api.config.TableRuleConfiguration;
import io.shardingsphere.api.config.strategy.StandardShardingStrategyConfiguration;
import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
/**
* mybatis 配置数据源类
*
*/
@Configuration
@MapperScan("mapper")
public class MybatisConfiguration {
@Value("${mybatis.basepackage}")
private String basePackage;
@Value("${mybatis.xmlLocation}")
private String xmlLocation;
@Value("${mybatis.typeAliasesPackage}")
private String typeAliasesPackage;
@Bean(name="shardingDataSource")
@Qualifier("shardingDataSource")
public DataSource getShardingDataSource() throws SQLException {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
// 分库分表逻辑,在这里不做代码展示
return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig,new ConcurrentHashMap(), properties);
}
@Bean(name="druidDataSource")
@Qualifier("druidDataSource")
public DataSource getDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("数据库驱动");
druidDataSource.setUrl("数据库链接");
druidDataSource.setUsername("用户名");
druidDataSource.setPassword("密码");
return druidDataSource ;
}
@Bean
@Primary
public DynamicDataSource dataSource(
@Qualifier("shardingDataSource")DataSource shardingDataSource,
@Qualifier("druidDataSource")DataSource druidDataSource) {
Map
/**
* 使用分库分表的数据源
*/
@UseDataSource(source=DatabaseType.SHARDING_DATA_SOURCE)
public List listByParams(Map map) {
List orders = orderMapper.listByParams(map);
return orders ;
}
/**
* 使用默认数据源
*/
public List listByParams2(Map map) {
List orders = orderMapper.listByParams(map);
return orders ;
}
// 也可以不使用注解,手动设置
public List listByParams2(Map map) {
// 切换数据源
DatabaseContextHolder.setDatabaseType(DatabaseType.SHARDING_DATA_SOURCE.getSource());
List orders = orderMapper.listByParams(map);
// 切换回默认的数据源
DatabaseContextHolder.clearDataSource();
return orders ;
}