一 mysql高可用方案
1.一主多从
2.组复制+mysql router
3.innodb cluster+mysql router
其他非官方的这里不说了
二 读写分离方案
主要两种方案
- 使用中间件
- 自己配置多数据源
可以根据具体的情况来做具体的分析,各有优缺点
1.使用中间件
优点
- 项目不需要改变
缺点
- 中间件都是第三方开发,稳定性,及版本维护是个隐患
- 中间多了层,势必对速度有影响
- 运维是否愿意使用
目前市面上使用的主要的中间建
- mysq router
这个其实并不能实现读写分离,也需要工程自己配置多数据源 ,他是一个mysql官方提供的中间件,可以和msyql的组复制,innodb cluster结合使用比较方便,可以动态检查集群几点的切换 - MaxScale
MaxScale是maridb开发的一个mysql数据中间件,其配置简单,能够实现读写分离,并且可以根据主从状态实现写库的自动切换,如果只需要读写分离,个人比较推荐这个 - mycat
MyCat是阿里基于Java语言编写的数据库中间件,是一个实现了MySql协议的服务器,其核心功能是分库分表。配合数据库的主从模式还可以实现读写分离
可以参考 https://www.jianshu.com/p/c8973edc550a
2.boot工程配置多数据源
- 配置文件
config.datasource.username=root
config.datasource.password=888888
config.datasource.driver-class-name=com.mysql.jdbc.Driver
config.datasource.url=jdbc:mysql://192.168.100.120:3307/config?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false
tx.datasource.username=root
tx.datasource.password=888888
tx.datasource.driver-class-name=com.mysql.jdbc.Driver
tx.datasource.url=jdbc:mysql://192.168.100.120:3307/tx?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false
- 创建不同的mapper包
- java Configuration
1) ConfigMybatisConfig.java
@Configuration
@MapperScan(basePackages = {"com.yu.txnotify.dao_config"}, sqlSessionTemplateRef = "configSqlSessionTemplate")
public class ConfigMybatisConfig {
@Bean(name = "configDataSource")
@Primary//必须加此注解,不然报错,下一个类则不需要添加
@ConfigurationProperties(prefix = "config.datasource")
public DataSource configDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory configSqlSessionFactory(@Qualifier("configDataSource") DataSource dataSource) throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean
public SqlSessionTemplate configSqlSessionTemplate(@Qualifier("configSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception
{
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);//使用上面配置的Factory
return template;
}
}
2) TxMybatisConfig.java
@Configuration
@MapperScan(basePackages = {"com.yu.txnotify.dao_tx"}, sqlSessionTemplateRef = "txSqlSessionTemplate")
public class TxMybatisConfig {
@Bean(name = "txDataSource")
@ConfigurationProperties(prefix = "tx.datasource")
public DataSource txDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory txSqlSessionFactory(@Qualifier("txDataSource") DataSource dataSource) throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean
public SqlSessionTemplate txSqlSessionTemplate(@Qualifier("txSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception
{
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);//使用上面配置的Factory
return template;
}
}