spring boot + mybatis(通用mapper) druid多数据源切换配置
项目结构:
1.配置数据源
2.动态数据源切换
3.注册动态数据源
package com.xe.demo.common.ds;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
/**
* 动态数据源注册
* @author CZH
*/
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);
// 数据源配置信息
private PropertyValues dataSourcePropertyValues;
// 默认数据源
private DataSource defaultDataSource;
// 动态数据源
private Map<String, DataSource> dynamicDataSources = new HashMap<>();
/**
* 加载多数据源配置
*/
@Override
public void setEnvironment(Environment env) {
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
String dsPrefixs = propertyResolver.getProperty("datasources");
for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
Map<String, Object> map = propertyResolver.getSubProperties(dsPrefix + ".");
DataSource ds = initDataSource(map);
// 设置默认数据源
if ("ds".equals(dsPrefix)) {
defaultDataSource = ds;
} else {
dynamicDataSources.put(dsPrefix, ds);
}
dataBinder(ds, env);
}
}
/**
* 初始化数据源
* @param map
* @return
*/
@SuppressWarnings("unchecked")
public DataSource initDataSource(Map<String, Object> map) {
String driverClassName = map.get("driverClassName").toString();
String url = map.get("url").toString();
String username = map.get("username").toString();
String password = map.get("password").toString();
String dsType = map.get("dsType").toString();
Class<DataSource> dataSourceType;
DataSource dataSource = null;
try {
dataSourceType = (Class<DataSource>) Class.forName(dsType);
dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
.username(username).password(password).type(dataSourceType).build();;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dataSource;
}
/**
* 加载数据源配置信息
* @param dataSource
* @param env
*/
private void dataBinder(DataSource dataSource, Environment env) {
RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
dataBinder.setIgnoreNestedProperties(false);// false
dataBinder.setIgnoreInvalidFields(false);// false
dataBinder.setIgnoreUnknownFields(true);// true
if (dataSourcePropertyValues == null) {
Map<String, Object> values = new RelaxedPropertyResolver(env, "datasource").getSubProperties(".");
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
}
/**
* 注册数据源been
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 将主数据源添加到更多数据源中
targetDataSources.put("dataSource", defaultDataSource);
// 添加更多数据源
targetDataSources.putAll(dynamicDataSources);
// 创建DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition);
logger.info("多数据源注册成功");
}
}
4.动态数据源注解切点
5.通过切点切换数据源
6.在service层通过注解切换不同数据源
package com.xe.demo.service;
import java.util.Date;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.xe.demo.common.ds.TargetDataSource;
import com.xe.demo.common.pojo.AjaxResult;
import com.xe.demo.common.pojo.PageAjax;
import com.xe.demo.common.utils.AppUtil;
import com.xe.demo.model.AuthUser;
@Service
public class UserService extends AbstratService<AuthUser> {
/**
* 使用默认数据源
* @param page
* @param user
* @return
*/
public PageAjax<AuthUser> queryUserDefPage(PageAjax<AuthUser> page, AuthUser user){
return queryPage(page, user);
}
@TargetDataSource("ds")
public PageAjax<AuthUser> queryUserDsPage(PageAjax<AuthUser> page, AuthUser user){
return queryPage(page, user);
}
@TargetDataSource("ds1")
public PageAjax<AuthUser> queryUserDs1Page(PageAjax<AuthUser> page, AuthUser user){
return queryPage(page, user);
}
@TargetDataSource("ds2")
public PageAjax<AuthUser> queryUserDs2Page(PageAjax<AuthUser> page, AuthUser user){
return queryPage(page, user);
}
/**
* 事务测试
* @param user
* @return
*/
@Transactional//添加事务
@TargetDataSource("ds1")
public AjaxResult addUser(AuthUser user) {
String str = AppUtil.getRandomString(5);
user.setUsername("user" + str);
user.setPassword("123456");
user.setEmail(str + "@test.com");
user.setRoleid(5);
user.setUseable(1);
user.setAddtime(new Date());
int ret = insert(user);
if(ret > 0){
System.out.println(1/0);
user = new AuthUser();
str = AppUtil.getRandomString(5);
user.setUsername("user" + str);
user.setPassword("123456");
user.setEmail(str + "@test.com");
user.setRoleid(5);
user.setUseable(1);
user.setAddtime(new Date());
}
return save(user);
}
}
7.启动项目
8.浏览器访问:http://localhost:8280
猜你喜欢
- Spring整合Mybatis实现动态数据源切换教程配置
- spring boot整合mybatis连接查询两个mysql数据源的配置实例
- mybatis代码自动生成器
- mybatis批量删除(逻辑删除)
- mybatis自动生成 实体类、接口、配置文件
- Mybatis入门教程之增删查实例
- mybatis plus实现简单的增删改查
- 自己搭建简易mybatis开发模板
- mybatis增删改查,关联查询,带数据库的demo
- mybatis反向工程自动生成entity+dao+映射文件mapper
- mybatis环境配置连接sqlserver实现查询实例
- spring mvc整合mybatis实现简单的分页
- /
- /demo-boot-multdata
- /demo-boot-multdata/.apt_generated
- /demo-boot-multdata/.classpath
- /demo-boot-multdata/.factorypath
- /demo-boot-multdata/.project
- /demo-boot-multdata/.settings
- /demo-boot-multdata/.settings/.jsdtscope
- /demo-boot-multdata/.settings/org.eclipse.core.resources.prefs
- /demo-boot-multdata/.settings/org.eclipse.jdt.apt.core.prefs
- /demo-boot-multdata/.settings/org.eclipse.jdt.core.prefs
- /demo-boot-multdata/src
- /demo-boot-multdata/src/main
- /demo-boot-multdata/src/main/java
- /demo-boot-multdata/src/main/java/com
- /demo-boot-multdata/src/main/java/com/xe
- /demo-boot-multdata/src/main/java/com/xe/demo
/demo-boot-multdata/src/main/java/com/xe/demo/Application.java
- /demo-boot-multdata/src/main/java/com/xe/demo/common
- /demo-boot-multdata/src/main/java/com/xe/demo/common/dao
- /demo-boot-multdata/src/main/java/com/xe/demo/common/ds
- /demo-boot-multdata/src/main/java/com/xe/demo
- /demo-boot-multdata/src/main/java/com/xe
- /demo-boot-multdata/src/main/java/com
- /demo-boot-multdata/src/main/java
- /demo-boot-multdata/src/main
- /demo-boot-multdata/.apt_generated
- /demo-boot-multdata
- mybatis代码自动生成器
- mybatis自动生成 实体类、接口、配置文件
- 原 Mybatis入门教程之增删查实例
- 原 mybatis反向工程自动生成entity+dao+映射文件mapper
- 原 mybatis环境配置连接sqlserver实现查询实例
- mybatis批量删除(逻辑删除)
- 原 自己搭建简易mybatis开发模板
- mybatis增删改查,关联查询,带数据库的demo
- 证 mybatis plus实现简单的增删改查
- mybatis新手入门学习项目代码及其框架搭建教程
- 原 mybatis基础学习,通过main函数测试数据库读写
- 原 spring mvc整合mybatis实现简单的分页