说起多数据源,一般都来用来解决主从模式或者业务比较复杂需要连接不同的分库来支持业务。本篇文章主要讲解后者的模式,利用AOP动态切换来达到项目访问不同数据源。
创建一个springboot工程,在其pom文件加入:
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.29version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
首先要将Spring Boot自带的DataSourceAutoConfiguration禁用,因为它会读取application.properties文件的spring.datasource.*属性并自动配置单数据源。在@SpringBootApplication注解中添加exclude属性即可
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
spring:
datasource:
#连接池设置
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 1
minIdle: 1
maxIdle: 2
maxActive: 5
#主数据源
ds-main:
url: jdbc:mysql://localhost:3306/multidb1?&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: root
driverClassName: com.mysql.jdbc.Driver
#额外数据源1
ds-1:
url: jdbc:mysql://localhost:3306/multidb2?&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: root
driverClassName: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath*:mapper/*.xml
type-aliases-package: com.chenjie.springboot.learn.entity
由于我们禁掉了自动数据源配置,因些下一步就需要手动将这些数据源创建出来:
@Configuration
public class DataSourceConfig {
//数据源1
@Bean(name = "datasource1")
@ConfigurationProperties(prefix = "spring.datasource.ds-main") // application.properteis中对应属性的前缀
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
//数据源2
@Bean(name = "datasource2")
@ConfigurationProperties(prefix = "spring.datasource.ds-1") // application.properteis中对应属性的前缀
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
使用动态数据源的初衷,是能在应用层做到读写分离,即在程序代码中控制不同的查询方法去连接不同的库。除了这种方法以外,数据库中间件也是个不错的选择,它的优点是数据库集群对应用来说只暴露为单库,不需要切换数据源的代码逻辑。我们通过自定义注解 + AOP的方式实现数据源动态切换。首先定义一个DataSourceContextHolder , 用于保存当前线程使用的数据源名:
public class DataSourceContextHolder {
private static final Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);
/**
* 默认数据源
*/
public static final String DEFAULT_DS = "datasource1";
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 设置数据源名
public static void setDB(String dbType) {
logger.info("切换到{"+dbType+"}数据源");
contextHolder.set(dbType);
}
// 获取数据源名
public static String getDB() {
return (contextHolder.get());
}
// 清除数据源名
public static void clearDB() {
contextHolder.remove();
}
}
然后自定义一个javax.sql.DataSource接口的实现,这里只需要继承Spring为我们预先实现好的父类AbstractRoutingDataSource即可:
public class DynamicDataSource extends AbstractRoutingDataSource {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
protected Object determineCurrentLookupKey() {
logger.info("数据源为"+DataSourceContextHolder.getDB());
return DataSourceContextHolder.getDB();
}
}
创建动态数据源:
在DataSourceConfig 中添加如下代码
/**
* 动态数据源: 通过AOP在不同数据源之间动态切换
* @return
*/
@Primary
@Bean(name = "dynamicDataSource")
public DataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 默认数据源
dynamicDataSource.setDefaultTargetDataSource(dataSource1());
// 配置多数据源
Map<Object, Object> dsMap = new HashMap();
dsMap.put("datasource1", dataSource1());
dsMap.put("datasource2", dataSource2());
dynamicDataSource.setTargetDataSources(dsMap);
return dynamicDataSource;
}
/**
* 配置@Transactional注解事物
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dynamicDataSource());
}
自定义注释@DS用于在编码时指定方法使用哪个数据源:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface DS {
String value() default "datasource1";
}
编写AOP切面,实现切换逻辑:
@Aspect
@Component
public class DynamicDataSourceAspect {
@Before("@annotation(DS)")
public void beforeSwitchDS(JoinPoint point){
//获得当前访问的class
Class<?> className = point.getTarget().getClass();
//获得访问的方法名
String methodName = point.getSignature().getName();
//得到方法的参数的类型
Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DEFAULT_DS;
try {
// 得到访问的方法对象
Method method = className.getMethod(methodName, argClass);
// 判断是否存在@DS注解
if (method.isAnnotationPresent(DS.class)) {
DS annotation = method.getAnnotation(DS.class);
// 取出注解中的数据源名
dataSource = annotation.value();
}
} catch (Exception e) {
e.printStackTrace();
}
// 切换数据源
DataSourceContextHolder.setDB(dataSource);
}
@After("@annotation(DS)")
public void afterSwitchDS(JoinPoint point){
DataSourceContextHolder.clearDB();
}
}
完成上述配置后,在先前SqlSessionFactory配置中指定使用DynamicDataSource就可以在Service中愉快的切换数据源了。
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
//使用数据源1查询
@DS("datasource1")
public List<User> findUserList1(){
return userMapper.findUserList();
}
//使用数据源2查询
@DS("datasource2")
public List<User> findUserList2(){
return userMapper.findUserList();
}
@DS("datasource1")
public User findUser1(int id) {
return userMapper.findUser(id);
}
@DS("datasource2")
public User findUser2(int id){
return userMapper.findUser(id);
}
@DS("datasource1")
public int add1(User user){
return userMapper.add(user);
}
@DS("datasource2")
public int add2(User user){
return userMapper.add(user);
}
@DS("datasource1")
public int delete1(int id){
return userMapper.delete(id);
}
@DS("datasource2")
public int delete2(int id){
return userMapper.delete(id);
}
@DS("datasource1")
public int update1(User user){
return userMapper.update(user);
}
@DS("datasource2")
public int update2(User user){
return userMapper.update(user);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/list")
public List<User> findUserList() {
return userService.findUserList1();
}
@GetMapping(value = "/{id}")
public User findUser(@PathVariable("id") int id) {
return userService.findUser1(id);
}
@PutMapping(value = "/{id}")
public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "age", required = true) int age) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
if (0 < userService.update1(user)) {
return "success";
} else {
return "fail";
}
}
@DeleteMapping(value = "/{id}")
public String delete(@PathVariable(value = "id") int id) {
if (0 < userService.delete1(id)) {
return "success";
} else {
return "fail";
}
}
@PostMapping(value = "/add")
public String postAccount(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
@RequestParam(value = "age") int age) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
if (0 < userService.add1(user)) {
return "success";
} else {
return "fail";
}
}
@GetMapping(value = "/db2/list")
public List<User> findUserList2() {
return userService.findUserList2();
}
@GetMapping(value = "/db2/{id}")
public User findUser2(@PathVariable("id") int id) {
return userService.findUser2(id);
}
@PutMapping(value = "/db2/{id}")
public String updateAccount2(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "age", required = true) int age) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
if (0 < userService.update2(user)) {
return "success";
} else {
return "fail";
}
}
@DeleteMapping(value = "/db2/{id}")
public String delete2(@PathVariable(value = "id") int id) {
if (0 < userService.delete2(id)) {
return "success";
} else {
return "fail";
}
}
@PostMapping(value = "/db2/add")
public String postAccount2(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
@RequestParam(value = "age") int age) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
if (0 < userService.add2(user)) {
return "success";
} else {
return "fail";
}
}
}
源码下载:https://github.com/chenjary/SpringBoot