For the master-slave architecture process of the database, please refer to https://www.cnblogs.com/cloudhere/p/10991520.html .
Java about the application of the master and slave write here:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
@Aspect
@Component
@Order(1)
public class DataSourceAop {
//公共参数,创建时间
private static final String CREATE_DATE = "createDate";
//修改时间
private static final String UPDATE_DATE = "updateDate";
/**
* 只读方法的设置
*/
@Pointcut("execution(* com.haozi.miaoshaproject.service.impl..*.select*(..))"
+ "|| execution(* com.haozi.miaoshaproject.service.impl..*.find*(..))"
+ "|| execution(* com.haozi.miaoshaproject.service.impl..*.get*(..))")
public void readonlyPointcut(){
}
/**
* 读写方法的设置
*/
@Pointcut("execution(* com.haozi.miaoshaproject.service.impl..*.save*(..))"
+ "|| execution(* com.haozi.miaoshaproject.service.impl..*.update*(..))"
+ "|| execution(* com.haozi.miaoshaproject.service.impl..*.insert*(..))"
+ "|| execution(* com.haozi.miaoshaproject.service.impl..*.add*(..))")
public void writePointcut(){
}
/**
* 具体切入
* @param joinPoint
*/
@Before("writePointcut()")
public void setDataBaseMaster(JoinPoint joinPoint) {
DynamicDataSource.setDataBaseType(DynamicDataSource.DatabaseType.primaryDataSource);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Object[] args = joinPoint.getArgs();
if (args != null && args.length > 0) {
Object argument = args[0];
BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
System.out.println("----------主库------" + signature.getMethod().getName());
//新增时设置创建时间
if(signature.getMethod().getName().contains("add")
|| signature.getMethod().getName().contains("save")
|| signature.getMethod().getName().contains("insert")){
// 设置创建时间和修改时间
if (beanWrapper.isWritableProperty(CREATE_DATE)) {
beanWrapper.setPropertyValue(CREATE_DATE, new Date());
}
}
//修改时间设置
if (beanWrapper.isWritableProperty(UPDATE_DATE)) {
beanWrapper.setPropertyValue(UPDATE_DATE, new Date());
}
}
}
/**
* 具体切入
* @param joinPoint
*/
@Before("readonlyPointcut()")
public void setDataBaseSlave(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
DynamicDataSource.setDataBaseType(DynamicDataSource.DatabaseType.readonlyDataSource);
System.out.println("----------从库------" + signature.getMethod().getName());
}
}
@Configuration
public class DruidConfig {
@Primary
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.master")
public DataSource druidPrimary(){
return new DruidDataSource();
}
@Bean(name = "readonlyDataSource")
@Qualifier("readonlyDataSource")
@ConfigurationProperties(prefix="spring.datasource.slave")
public DataSource druidReadonly(){
return new DruidDataSource();
}
/**
* 配置Druid的监控
* 1.配置一个管理后台的Servlet,对数据库进行可视化管理
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean =new ServletRegistrationBean(new StatViewServlet() , "/druid/*");
Map<String,String> initParams=new HashMap<>();
initParams.put("loginUsername", "root");
initParams.put("loginPassword", "admin");
initParams.put("allow", "");//默认就是允许所有访问。
//initParams.put("deny","");
//拒绝访问的ip
bean.setInitParameters(initParams);
return bean;
}
/**
* 2.配置一个监控的filter
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean =new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams=new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//拦截所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* 列出所有的数据源key(常用数据库名称来命名)
* 注意:
* 1)这里数据源与数据库是一对一的
*/
public enum DatabaseType {
//主库
primaryDataSource,
//从库
readonlyDataSource
}
private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();
public static void setDataBaseType(DatabaseType type){
contextHolder.set(type);
}
public static DatabaseType getDataBaseType(){
DatabaseType db = contextHolder.get();
if (db == null)
db = DatabaseType.primaryDataSource;
return db;
}
public Object determineCurrentLookupKey() {
return getDataBaseType();
}
/**
* 清理链接类型
*/
public static void clearDbType() {
contextHolder.remove();
}
}
@Configuration
@MapperScan(value = "com.haozi.miaoshaproject.dao")//,sqlSessionTemplateRef = "sqlSessionTemplatePrimary"
public class MybatisConfig {
/**
* @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
* @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)
*/
@Bean
public DynamicDataSource dataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource,
@Qualifier("readonlyDataSource") DataSource readonlyDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DynamicDataSource.DatabaseType.primaryDataSource, primaryDataSource);
targetDataSources.put(DynamicDataSource.DatabaseType.readonlyDataSource, readonlyDataSource);
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
dataSource.setDefaultTargetDataSource(primaryDataSource);// 默认的datasource设置为myTestDbDataSource
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource dataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//配置xml目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources("classpath*:mapping/*.xml"));
return bean.getObject();
}
/**
* 配置事务管理器
*/
@Bean
public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
return new DataSourceTransactionManager(dataSource);
}
}
The main idea is to use aspect monitoring to implement class methods, and different methods to switch between different data sources.