赞
踩
@DS
注解使用):<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
主数据源使用
master
做主库标识,在使用的时候不需要显示标识,默认使用的都是该库。
也可指定主数据源(不指定默认查找master标识的):spring.datasource.dynamic.primary=master如果使用其他字符(db_name1),如:spring.datasource.dynamic.datasource.
db_name1
.driver-class-name),则使用时需要显示声明@DS("db_name1")
使用的数据库。
# 主数据源库(程序会默认使用master标识的主库)
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=utf-8
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=1234
# 声明默认的主数据源(不配置的话,默认查找master标识的数据源,也可改为其他数据源标识)
spring.datasource.dynamic.primary=master
# 忽略默认自动注入druid(此步骤必须有,否则动态数据源无效)
spring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
# 其他数据源(使用时需要使用`@DS("myztree")`注解声明使用的数据库)
spring.datasource.dynamic.datasource.myztree.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.myztree.url=jdbc:mysql://127.0.0.1:3306/myztree?useUnicode=true&characterEncoding=utf-8
spring.datasource.dynamic.datasource.myztree.username=root
spring.datasource.dynamic.datasource.myztree.password=1234
# ==== Modify the default tomcat port (default:8080) ====================================================
server.port=8081
# ====== mybatis resource and mapper file location (★★★★★) ================================================
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# mybatis.config-location=classpath:mybatis-config.xml
mybatis.type-aliases-package = cn.xiyou.pojo
动态数据源说明:
DruidDataSourceAutoConfigure默认会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等。动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错。
【解决方法】:忽略DruidDataSourceAutoConfigure.
第一种:在上述配置文件排除,spring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
第二种:在项目启动类上排除:@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
不需做任何操作
,和之前单数据库一样)import cn.xiyou.mapper.DeptMapper;
import cn.xiyou.pojo.Dept;
import cn.xiyou.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
@Override
public List<Dept> findAll() {
return deptMapper.findAll();
}
@Override
public List<Dept> findAllByOrgCode(String orgCode) {
return deptMapper.findAllByOrgCode(orgCode);
}
}
@DS("myztree")
注解声明使用的数据库)package cn.xiyou.service.impl;
import cn.xiyou.mapper.TreeMapper;
import cn.xiyou.pojo.ZTree;
import cn.xiyou.service.TreeService;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@DS("myztree")
@Service
public class TreeServiceImpl implements TreeService {
@Autowired
private TreeMapper treeMapper;
@Override
public List<ZTree> selectThreeTreeNode() {
return treeMapper.selectThreeTreeNode();
}
}
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- MySQL依赖包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!-- aspect增强 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>compile</scope>
</dependency>
# ======MySQL Database configure (单库数据源配置) =================================================================
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=utf-8
#spring.datasource.username=root
#spring.datasource.password=1234
# druid数据源(此配置不影响多数据源的切换配置)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 忽略jdbc数据源的自动装配,我们自定义多数据源。也可在启动类上了忽略:@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
# (1)主数据源
spring.datasource.druid.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.master.jdbc-url=jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=utf-8
spring.datasource.druid.master.username=root
spring.datasource.druid.master.password=1234
# (2)从数据源
spring.datasource.druid.slave.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.slave.jdbc-url=jdbc:mysql://127.0.0.1:3306/myztree?useUnicode=true&characterEncoding=utf-8
spring.datasource.druid.slave.username=root
spring.datasource.druid.slave.password=1234
#从数据源开关/默认关闭
#spring.datasource.druid.slave.enabled=true
# (3)第三个数据源
spring.datasource.druid.third.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.third.jdbc-url=jdbc:mysql://127.0.0.1:3306/succez?useUnicode=true&characterEncoding=utf-8
spring.datasource.druid.third.username=root
spring.datasource.druid.third.password=1234
################################################################################################################
# 其他配置
# ==== Modify the default tomcat port (default:8080) ====================================================
server.port=8081
# ====== mybatis resource and mapper file location (mybatis配置) ================================================
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
#mybatis.config-location=classpath:mybatis-config.xml
mybatis.type-aliases-package = cn.xiyou.pojo
# ======== Set the log4j configure (日志) ==================================================================
logging.level.cn.xiyou.mapper=debug
#logging.level.org.springframework=debug
#logging.path=d:/log.log
# ========= Modify the default context path (Version 2.0 or higher). (default:/) (上下文路径)========================
#server.servlet.context-path=/spring-boot
# ==== Thymeleaf fot jsp (模板引擎) ===========================================================================
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=false
提示: 如果不忽略jdbc数据源自动装配,启动会报错:循环引用错。
忽略jdbc数据源自动装配的方法:
第一种:在上述配置文件排除,spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
第二种:在项目启动类上排除:@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
(1)数据源枚举类型
package cn.xiyou.config;
/**
* @author: zhangxiaohu
* @date: 2021/6/25 21:57
* @Description:
*/
public enum DataSourceType {
/**
* 主库
*/
MASTER,
/**
* 从库
*/
SLAVE,
/**
* 第三个库
*/
THIRD
}
(2)线程动态存储数据源
package cn.xiyou.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 线程动态存储数据源
*
* @author: zhangxiaohu
* @date: 2021/6/25 21:51
* @Description:
*/
public class DynamicDataSourceContextHolder {
public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
/**
* 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
* 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
*/
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
/**
* 设置数据源变量
*
* @param dataSourceType
*/
public static void setDataSourceType(String dataSourceType) {
log.info("切换到{}数据源", dataSourceType);
CONTEXT_HOLDER.set(dataSourceType);
}
/**
* 获取数据源变量
*
* @return
*/
public static String getDataSourceType() {
return CONTEXT_HOLDER.get();
}
/**
* 清空数据源变量
*/
public static void clearDataSourceType() {
CONTEXT_HOLDER.remove();
}
}
(3)配合Bean:代码配置多个数据源(对应配置文件中的数据源)
package cn.xiyou.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 注入数据源
*
* @author: zhangxiaohu
* @date: 2021/6/25 21:55
* @Description:
*/
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.master") //主数据源前缀
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave") //从数据源前缀
// @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.third") //第三个数据源前缀
public DataSource thirdDataSource() {
return DataSourceBuilder.create().build();
}
/**
* 注册数据源
* @param masterDataSource 主数据源
* @param slaveDataSource 从数据源
* @param thirdDataSource 第三个数据源
* @return
*/
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource, DataSource thirdDataSource) {
Map<Object, Object> targetDataSourcesMap = new HashMap<>();
//主数据源
targetDataSourcesMap.put(DataSourceType.MASTER.name(), masterDataSource);
//从数据源
targetDataSourcesMap.put(DataSourceType.SLAVE.name(), slaveDataSource);
//第三个数据源
targetDataSourcesMap.put(DataSourceType.THIRD.name(), thirdDataSource);
// 设置默认数据源、其他数据源
return new DynamicDataSource(masterDataSource, targetDataSourcesMap);
}
}
(4)注册默认数据源、和其他数据源
package cn.xiyou.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
/**
* @author: zhangxiaohu
* @date: 2021/6/25 21:53
* @Description:
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
// 设置默认数据源、其他数据源
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSourcesMap) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSourcesMap);
super.afterPropertiesSet();//@xiao 此行代码可省略,不影响多数据源的使用
}
/**
* 根据Key获取数据源的信息
*
* @return
*/
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
(5)自定义切换数据源的注解
package cn.xiyou.config;
import java.lang.annotation.*;
/**
* 定义切换数据源的注解
*
* @author: zhangxiaohu
* @date: 2021/6/25 21:59
* @Description:
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
/**
* 切换数据源名称
*/
DataSourceType value() default DataSourceType.MASTER;
}
(6)aop方式拦截(5)中的自定义注解, 动态切换数据源
package cn.xiyou.advice;
import cn.xiyou.config.DataSource;
import cn.xiyou.config.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @author: zhangxiaohu
* @date: 2021/6/25 22:00
* @Description:
*/
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
private Logger log = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(cn.xiyou.config.DataSource)")
public void dsPointCut() {
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DataSource dataSource = method.getAnnotation(DataSource.class);
if (dataSource != null) {
log.info("【before数据源名】" + dataSource.value().name());
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
log.info("【after数据源名】" + dataSource.value().name());
}
Object obj = null;
try {
obj = point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
return obj;
}
}
不需做任何操作
,和之前单数据库一样)package cn.xiyou.mapper;
import java.util.List;
import cn.xiyou.config.DataSource;
import cn.xiyou.config.DataSourceType;
import cn.xiyou.pojo.Dept;
import org.apache.ibatis.annotations.Param;
public interface DeptMapper {
/**
* 获取所有部门信息
*
* @return
*/
// @DataSource(value = DataSourceType.MASTER)
List<Dept> findAll();
/**
* 根据机构编码获取所有部门信息
* @param orgCode
* @return
*/
List<Dept> findAllByOrgCode(@Param("orgCode") String orgCode);
}
package cn.xiyou.mapper;
import cn.xiyou.config.DataSource;
import cn.xiyou.config.DataSourceType;
import cn.xiyou.pojo.ZTree;
import java.util.List;
public interface TreeMapper {
/**
* 获取3个tree节点信息
*
* @return
*/
@DataSource(value = DataSourceType.SLAVE)
List<ZTree> selectThreeTreeNode();
}
package cn.xiyou.mapper;
import cn.xiyou.config.DataSource;
import cn.xiyou.config.DataSourceType;
import cn.xiyou.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
/**
* 获取所有用户信息
*
* @return
*/
@DataSource(value = DataSourceType.THIRD)
@Select("select id,name,age from user")
List<User> findAll();
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。