SpringBoot动态数据源(yml配置,多数据源⾃动切换)
1、在启动类添加注解,注册动态多数据源:
@SpringBootApplication
@Import({DynamicDataSourceRegister.class}) // 注册动态多数据源
public class OrangeplusApplication extends WebMvcConfigurerAdapter {
protected final static Logger logger = Logger(OrangeplusApplication.class);
public static void main(String[] args) {
SpringApplication.run(OrangeplusApplication.class, args);
logger.info("Application is success!");
}
}
2、yml配置⽂件中数据源配置内容为:
spring:
profiles: dev
datasource:
url: jdbc:mysql://127.0.0.1:3306/orangeplus?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull username: root
password: 123456
driver-class-name: sql.jdbc.Driver
# 更多数据源
custom:
profiles: dev
datasource:
springboot aopnames: ds1,ds2
ds1:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521:oracle
username: root
password: orcl#ncu
ds2:
driver-class-name: sql.jdbc.Driver
url: jdbc:mysql://localhost:3306/orangeplus2?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull username: root
password: 123456
3、在需要的⽅法上使⽤注解指定数据源,简单代码⽰例:
@Service
public class StudentService {
@Autowired
private JdbcTemplate jdbcTemplate;
// MyBatis的Mapper⽅法定义接⼝
@Autowired
private StudentMapper studentMapper;
@TargetDataSource(name="ds2")
public List<Student> likeName(String name){
return studentMapper.likeName(name);
}
public List<Student> likeNameByDefaultDataSource(String name){
public List<Student> likeNameByDefaultDataSource(String name){
return studentMapper.likeName(name);
}
/**
* 不指定数据源使⽤默认数据源
*/
public List<Student> getList(){
String sql = "SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT"; return (List<Student>) jdbcTemplate.query(sql, new RowMapper<Student>(){
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student stu = new Student();
stu.Int("ID"));
stu.Int("AGE"));
stu.String("NAME"));
stu.String("SCORE_SUM"));
stu.String("SCORE_AVG"));
return stu;
}
});
}
/**
* 指定数据源
*/
@TargetDataSource(name="ds1")
public List<Student> getListByDs1(){
String sql = "SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT"; return (List<Student>) jdbcTemplate.query(sql, new RowMapper<Student>(){
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student stu = new Student();
stu.Int("ID"));
stu.Int("AGE"));
stu.String("NAME"));
stu.String("SCORE_SUM"));
stu.String("SCORE_AVG"));
return stu;
}
});
}
/**
* 指定数据源
*/
@TargetDataSource(name="ds2")
public List<Student> getListByDs2(){
String sql = "SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT"; return (List<Student>) jdbcTemplate.query(sql, new RowMapper<Student>(){
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student stu = new Student();
stu.Int("ID"));
stu.Int("AGE"));
stu.String("NAME"));
stu.String("SCORE_SUM"));
stu.String("SCORE_AVG"));
return stu;
}
});
}
}
要注意的是,在使⽤MyBatis时,注解@TargetDataSource 不能直接在接⼝类Mapper上使⽤。 按上⾯的代码中StudentMapper为接⼝,实例代码如下:
public interface StudentMapper {
// 多数据源注解 @TargetDataSource 不可以在这⾥使⽤
List<Student> likeName(String name);
Student getById(int id);
String getNameById(int id);
}
请将下⾯⼏个类放到Spring Boot项⽬中:
DynamicDataSource.java
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
DataSourceType();
}
}
DynamicDataSourceAspect.java
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执⾏
@Component
public class DynamicDataSourceAspect {
private static final Logger logger = Logger(DynamicDataSourceAspect.class);
@Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
String dsId = ds.name();
if (!ainsDataSource(dsId)) {
<("数据源[{}]不存在,使⽤默认数据源 > {}", ds.name(), Signature());
} else {
logger.debug("Use DataSource : {} > {}", ds.name(), Signature());
DynamicDataSourceContextHolder.setDataSourceType(ds.name());
}
}
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), Signature());
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
DynamicDataSourceContextHolder.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() {
();
}
public static void clearDataSourceType() {
}
/
**
* 判断指定DataSrouce当前是否存在
*
* @param dataSourceId
*/
public static boolean containsDataSource(String dataSourceId){
ains(dataSourceId);
}
}
DynamicDataSourceRegister.java
/**
* 动态数据源注册<br/>
* 启动动态数据源请在启动类中(如SpringBootSampleApplication)
* 添加 @Import(DynamicDataSourceRegister.class)
*
*/
public class DynamicDataSourceRegister
implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = Logger(DynamicDataSourceRegister.class);
private ConversionService conversionService = new DefaultConversionService();
private PropertyValues dataSourcePropertyValues;
// 如配置⽂件中未指定数据源类型,使⽤该默认值
private static final Object DATASOURCE_TYPE_DEFAULT = "at.jdbc.pool.DataSource";
// private static final Object DATASOURCE_TYPE_DEFAULT =
// "com.zaxxer.hikari.HikariDataSource";
// 数据源
private DataSource defaultDataSource;
private Map<String, DataSource> customDataSources = new HashMap<>();
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 将主数据源添加到更多数据源中
targetDataSources.put("dataSource", defaultDataSource);
DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
// 添加更多数据源
targetDataSources.putAll(customDataSources);
for (String key : customDataSources.keySet()) {
DynamicDataSourceContextHolder.dataSourceIds.add(key);
}
}
// 创建DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = PropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
logger.info("Dynamic DataSource Registry");
}
/**
* 创建DataSource
*
* @param type
* @param driverClassName
* @param url
* @param username
* @param password
* @return
*/
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
try {
Object type = ("type");
if (type == null)
type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource
Class<? extends DataSource> dataSourceType;
dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
String driverClassName = ("driver-class-name").toString();
String url = ("url").toString();
String username = ("username").toString();
String password = ("password").toString();
DataSourceBuilder factory = ate().driverClassName(driverClassName).url(url) .username(username).password(password).type(dataSourceType);
return factory.build();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 加载多数据源配置
*/
@Override
public void setEnvironment(Environment env) {
initDefaultDataSource(env);
initCustomDataSources(env);
}
/
**
* 初始化主数据源
*
*/
private void initDefaultDataSource(Environment env) {
// 读取主数据源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource."); Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", Property("type"));
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论