springboot+mybatis-plus+多数据源配置,实现分表分库的数据访问
经过上一篇springboot+mybatis-plus的配置后,这次多数据源配置没有遇到太大的问题。参考了原作感谢这位仁兄文档的帮助,多数据源利用AbstractRoutingDataSource实现动态数据源切换,中间利用了切面和上下文获取的功能实现。我的开发环境是springboot2.1.4pom.xml<!-- mysql驱动 --><dependen...
·
经过上一篇springboot+mybatis-plus的配置后,这次多数据源配置没有遇到太大的问题。参考了 原作 感谢这位仁兄文档的帮助,多数据源利用AbstractRoutingDataSource实现动态数据源切换,中间利用了切面和上下文获取的功能实现。
我的开发环境是springboot2.1.4,项目结构是:
pom.xml
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
application.yml
server:
port: 8080
#mysql
spring:
datasource:
druid:
db1:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/local?useUnicode=true&characterEncoding=utf8
initialSize: 5
minIdle: 5
maxActive: 20
db2:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
initialSize: 5
minIdle: 5
maxActive: 20
#mybatis-plus 映射文件可以在配置文件中配置,也可以在配置类中配置,两种方式都可以
#路径必须正确,不然会报错Invalid bound statement (not found)
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
下边就是关于多数据源的配置了
DataSource.java
import com.example.mybatisplus.config.customenum.DataSourceEnum;
import java.lang.annotation.*;
/**
* 自定义注解
* @author leiwenwei
* 类 和 方法生效
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
DataSourceEnum value() default DataSourceEnum.DB1;
}
DataSourceAspect.java
import com.example.mybatisplus.config.annotation.DataSource;
import com.example.mybatisplus.config.contextholder.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 数据源切面配置
* Order设置优先级
* @author leiwenwei
*/
@Component
@Slf4j
@Aspect
@Order(-1)
public class DataSourceAspect {
/**
* 设置切面范围
*/
@Pointcut("@within(com.example.mybatisplus.config.annotation.DataSource) || @annotation(com.example.mybatisplus.config.annotation.DataSource)")
public void pointCut(){
}
/**
* 添加数据源上下文
* @param dataSource
*/
@Before("pointCut() && @annotation(dataSource)")
public void doBefore(DataSource dataSource){
log.info("选择数据源---"+dataSource.value().getValue());
DataSourceContextHolder.setDataSource(dataSource.value().getValue());
}
/**
* 清除数据源上下文
*/
@After("pointCut()")
public void doAfter(){
DataSourceContextHolder.clear();
}
}
DataSourceContextHolder.java
/**
* 定义数据源上下文
* @author leiwenwei
*/
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
/**
* 设置数据源
* @param db
*/
public static void setDataSource(String db){
contextHolder.set(db);
}
/**
* 取得当前数据源
* @return
*/
public static String getDataSource(){
return contextHolder.get();
}
/**
* 清除上下文数据
*/
public static void clear(){
contextHolder.remove();
}
}
DataSourceEnum.java
/**
* 数据源枚举类
* @author leiwenwei
*/
public enum DataSourceEnum {
/**
* 数据库1
*/
DB1("db1"),
/**
* 数据库2
*/
DB2("db2");
private String value;
DataSourceEnum(String value){this.value=value;}
public String getValue() {
return value;
}
}
MultipleDataSource.java
import com.example.mybatisplus.config.contextholder.DataSourceContextHolder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 多数据源路由
*
* @author leiwenwei
*/
public class MultipleDataSource extends AbstractRoutingDataSource {
/**
* 重写determineCurrentLookupKey(),通过DataSourceContextHolder 获取数据源变量,用于当作lookupKey取出指定的数据源
* determineCurrentLookupKey,该方法返回一个Object,一般是返回字符串
*
* @return
*/
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}
MyBatiesPlusConfiguration.java
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.example.mybatisplus.config.customenum.DataSourceEnum;
import com.example.mybatisplus.config.multidatasource.MultipleDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
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.context.annotation.Profile;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* mybatis-plus配置
*
* @author leiwenwei
*/
@Configuration
@MapperScan("com.example.mybatisplus.mapper")
public class MyBatiesPlusConfiguration {
/**
* 分页插件,自动识别数据库类型
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
/**
* SQL执行效率插件
* 设置 dev test 环境开启
*/
@Bean
@Profile({"dev", "qa"})
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000);
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
public DataSource db1() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource db2() {
return DruidDataSourceBuilder.create().build();
}
/**
* 动态数据源配置
*
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(@Qualifier("db1") DataSource db1, @Qualifier("db2") DataSource db2) {
MultipleDataSource multipleDataSource = new MultipleDataSource();
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceEnum.DB1.getValue(), db1);
targetDataSources.put(DataSourceEnum.DB2.getValue(), db2);
//添加数据源
multipleDataSource.setTargetDataSources(targetDataSources);
//设置默认数据源db1
multipleDataSource.setDefaultTargetDataSource(db1);
return multipleDataSource;
}
/**
* 返回MybatisSqlSessionFactory
*
* @return
* @throws Exception
*/
@Bean("sqlSessionFactory")
public MybatisSqlSessionFactoryBean sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(db1(), db2()));
/**application.yml文件中已经配置,无需再配置
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*Mapper.xml"));
*/
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(new Interceptor[]{
paginationInterceptor()
});
return sqlSessionFactory;
}
}
以上配置完成之后,还需要在相应的方法或者类中加上@DataSource注解,我的例子中两个实现类,一个是类中的方法加了注解,一个是在类中加了注解,如下:
类加注解(所有的方法都会生效)
/**
* <p>
* Own服务实现类
* 在类上加@DataSource,绑定数据源DB1
* </p>
*
* @author leiwnewei123
* @since 2019-04-28
*/
@Service
@DataSource(DataSourceEnum.DB1)
public class OwnServiceImpl extends ServiceImpl<OwnDao, Own> implements OwnService {
@Autowired
private OwnDao ownDao;
@Override
public List<Own> getOwns() {
return ownDao.getOwns();
}
}
方法加注解(只对对应的方法生效)
/**
* <p>
* Car服务实现类
* 在类上加@DataSource,绑定数据源DB2
* </p>
*
* @author leiwnewei
* @since 2019-04-28
*/
@Service
public class CarServiceImpl extends ServiceImpl<CarDao, Car> implements CarService {
@Override
@DataSource(DataSourceEnum.DB2)
public boolean save(Car entity) {
return super.save(entity);
}
@Override
@DataSource(DataSourceEnum.DB2)
public boolean removeById(Serializable id) {
return super.removeById(id);
}
@Override
@DataSource(DataSourceEnum.DB2)
public boolean updateById(Car entity) {
return super.updateById(entity);
}
@Override
@DataSource(DataSourceEnum.DB2)
public Car getById(Serializable id) {
return super.getById(id);
}
@Override
@DataSource(DataSourceEnum.DB2)
public List<Car> list(Wrapper<Car> wrapper) {
return super.list(wrapper);
}
@Override
@DataSource(DataSourceEnum.DB2)
public IPage<Car> page(IPage<Car> page) {
return super.page(page);
}
@Override
@DataSource(DataSourceEnum.DB2)
public IPage<Car> page(IPage<Car> page, Wrapper<Car> wrapper) {
return super.page(page, wrapper);
}
}
以上配置完成后,就可以开始测试了----
测试类:(切记 得保证方法是可以找到对应数据源,不然会报错not exist)
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisplusApplicationTests {
@Autowired
private OwnService ownService;
@Autowired
private CarService carService;
@Test
public void contextLoads() {
List<Own> owns = ownService.getOwns();
System.out.println(owns);
Car car = new Car();
car.setCarName("吉利");
car.setPriceTicket(123);
System.out.println(carService.save(car)?"添加car成功!":"添加失败");
}
}
希望能帮到各位!!!
更多推荐
已为社区贡献1条内容
所有评论(0)