参考文档:https://www.jianshu.com/p/6b203f4926d5
作者:zenghi
一、环境及工具
1.Intellij IDEA 2019.2.2
2.MySQL8.x
3.Navicat for MySQL
4.Maven工程
5.Springboot2+MyBatis3+MySQL8+Swagger2+MybatisPlugin+Maven
二、注意事项(一般人不会看到底再动手所以写在前边)
1.注意导入的都是哪些包我都复制上来了
三、下面是配置类
pom.xml(springframework部分,其余自己需要什么加什么就行)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
application.yml(spring配置,根据自己情况改)
spring:
datasource:
temple:
driver-clss-name: com.mysql.cj.jdbc.Driver #MySQL8驱动字符串
jdbc-url: "jdbc:mysql://localhost:3306/temple?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC"
username: root
password: 123
example:
driver-clss-name: com.mysql.cj.jdbc.Driver
jdbc-url: "jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC"
username: root
password: 123
DataSource.java(可直接复制)
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Buckler
* @description 自定义注解,用于类或方法上,优先级:方法>类
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
DataSourceType value() default DataSourceType.temple;
}
DataSourceAspect.java(可直接复制)
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* @author Buckler
* @description
*/
@Aspect
@Component
public class DataSourceAspect {
@Before("@annotation(ds)")
public void beforeDataSource(DataSource ds) {
DataSourceType value = ds.value();
DataSourceContextHolder.setDataSource(value);
System.out.println("CurrentDataSource:" + value);
}
@After("@annotation(ds)")
public void afterDataSOurce(DataSource ds) {
DataSourceContextHolder.clearDataSource();
}
}
DataSourceContextHolder.java(可直接复制)
/**
* @author Buckler
* @description 动态数据源上下文管理:设置数据源,获取数据源,清除数据源
*/
public class DataSourceContextHolder {
//存放当前线程使用的而数据源类型
private static final ThreadLocal<DataSourceType> contextHolder = new ThreadLocal<>();
//设置数据源
public static void setDataSource(DataSourceType type) {
contextHolder.set(type);
}
//获取数据源
public static DataSourceType getDataSource() {
return contextHolder.get();
}
//清除数据源
public static void clearDataSource() {
contextHolder.remove();
}
}
DataSourceType.java(根据自己情况修改对应枚举)
/**
* @author Buckler
* @description 列出所有数据源
*/
public enum DataSourceType {
temple,
example,
}
DynamicDataSource.java(可直接复制)
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @author Buckler
* @description 动态数据源,每执行一次数据库,动态获取数据源
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}
MyBatisConfig.java(根据自己情况修改)
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @author Buckler
* @description MyBatis配置
*/
@Configuration
@MapperScan(basePackages = "com.example.dao")
public class MyBatisConfig {
@Primary
@Bean("templeDataSource")
@ConfigurationProperties(prefix = "spring.datasource.temple")
public DataSource templeDataSource() {
DataSource templeDataSource = DataSourceBuilder.create().build();
return templeDataSource;
}
@Bean("exampleDataSource")
@ConfigurationProperties(prefix = "spring.datasource.example")
public DataSource exampleDataSource() {
return DataSourceBuilder.create().build();
}
//这里可以按照exampleDataSource进行添加更多的数据源(注意要修改枚举类、yml、下边的Qualifier以及下边的map)
@Bean
public DynamicDataSource dataSource(@Qualifier("templeDataSource") DataSource templeDataSource,
@Qualifier("exampleDataSource") DataSource exampleDataSource) {
Map<Object, Object> map = new HashMap<>();
map.put(DataSourceType.temple, templeDataSource);
map.put(DataSourceType.example, exampleDataSource);
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(map);
dynamicDataSource.setDefaultTargetDataSource(templeDataSource);
return dynamicDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dynamicDataSource);
Resource[] resources = new
//这里要注意classpath的路径,具体看自己如何分包
PathMatchingResourcePatternResolver().getResources("classpath:com/example/mapper/*/*.xml");
factoryBean.setMapperLocations(resources);
return factoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
return new DataSourceTransactionManager(dynamicDataSource);
}
}
四、如何使用
只需要在Service类或Controller类里添加注解即可!代码如下:
@Service
public class UserService implements IUser {
@Autowired
private UserMapper userMapper;
@Override
@DataSource(DataSourceType.example) //这里确定所使用的数据源
public List<User> findAllUser() {
return userMapper.findAllUser();
}
}
网友评论