【开发进阶】——MySQL配置主从同步,代码层实现读写分离

前提

1、服务器环境 centos7
2、MySQL5.7
3、在两台机器完成MySQL的安装相关内容
4、框架ssm+数据连接池druid+p6spy

配置主从同步

主服务相关配置
1、在my.cnf中设置如下内容

server-id=1
log-bin=master-bin
log-bin-index=master-bin.index

2、创建用户,并授权

create user repl;
grant replication slave on *.* to 'repl'@'从服务器的ip地址' identified by 'mysql';
flush privileges;

3、查看主服务相关状态

show master status;

查询内容结果如下,牢记标注位置,下文需要用到
【开发进阶】——MySQL配置主从同步,代码层实现读写分离_第1张图片

从服务相关配置
1、在my.cnf中设置如下内容

server-id=2
relay-log-index=slave-relay-bin.index
relay-log=slave-relay-bin

2、与主服务器绑定,并开启主从同步

//master_log_file配置就是主服务器中标注的内容,偏移值,按照自己的实际情况填写
change master to master_host='主服务器ip地址',master_port=3306,master_user='repl',master_password='mysql',master_log_file='master-bin.000001',master_log_pos=0;
//开启主从同步
start slave;

3、查看主从同步状态

show slave status;

查看下图中标注处是否有错误,如图,则证明主从同步已经配置好了
【开发进阶】——MySQL配置主从同步,代码层实现读写分离_第2张图片


代码层实现读写分离

1、获取数据库类型

public class DynamicDataSourceHolder {
    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceHolder.class);
    private static ThreadLocal  contextHolder = new ThreadLocal <>();
    public static final String DB_MASTER = "master";
    public static final String DB_SLAVE = "slave";
    public static String getDbType() {
        String db = contextHolder.get();
        if (db == null) {
            db = DB_MASTER;
        }
        return db;
    }

    /**
     * 设置线程的dbType
     * @param str
     */
    public static void setDbType(String str) {
        log.debug("所使用的数据源为:" + str);
        contextHolder.set(str);
    }

    /**
     * 清理连接类型
     */
    public static void clearDBType() {
        contextHolder.remove();
    }
}

2、编写拦截器

@Intercepts({@Signature(type = Executor.class,method ="update",args = {MappedStatement.class,Object.class}),
@Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class})})
public class DynamicDataSourceInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceInterceptor.class);
    private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        boolean synchronizationActive = TransactionSynchronizationManager.isActualTransactionActive();
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        String lookupKey = DynamicDataSourceHolder.DB_MASTER;
        if (!synchronizationActive) {
            //读方法
            if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
//                selectKey为自增id查询主键(Select last_insert_id())方法,使用主库
                if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
                    lookupKey = DynamicDataSourceHolder.DB_MASTER;
                } else {
                    BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
                    String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("\\t\\n\\r", " ");
                    if (sql.matches(REGEX)) {
                        lookupKey = DynamicDataSourceHolder.DB_MASTER;
                    } else {
                        lookupKey = DynamicDataSourceHolder.DB_SLAVE;
                    }
                }
            } else {
                lookupKey = DynamicDataSourceHolder.DB_MASTER;
            }
        }
        log.debug("设置方法[{}]use[{}]Strategy,SqlCommanType[{}]..",ms.getId(),lookupKey,ms.getSqlCommandType().name());
        DynamicDataSourceHolder.setDbType(lookupKey);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }
    @Override
    public void setProperties(Properties properties) {

    }
}

3、数据源

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceHolder.getDbType();
    }
}

4、配置多数据源

    
    <context:property-placeholder location="classpath:db.properties"/>
    
    <bean id="abstractDataSourceDefault" abstract="true" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        
        <property name="initialSize" value="**"/>
        <property name="maxActive" value="**" />
        <property name="minIdle" value="**" />
        
        <property name="maxWait" value="**" />
        
        <property name="validationQuery" value="select 'x'"/>
        
        <property name="validationQueryTimeout" value="**"/>
        
        <property name="timeBetweenEvictionRunsMillis" value="**"/>
        
        <property name="testOnBorrow" value="true"/>
        
        <property name="testOnReturn" value="true"/>
        
        <property name="testWhileIdle" value="true"/>
        
        <property name="minEvictableIdleTimeMillis" value="**"/>
        
        <property name="poolPreparedStatements" value="false"/>
        
        <property name="maxPoolPreparedStatementPerConnectionSize" value="-1"/>
        
        <property name="filters" value="stat" />
        
        
        
        
        
        
        
    bean>
    
    <bean id="master" parent="abstractDataSourceDefault">
        <property name="url" value="${jdbc.master.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    bean>
    
    <bean id="slave" parent="abstractDataSourceDefault">
        <property name="url" value="${jdbc.slave.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    bean>

    <bean id="dymicDataSources" class="com.***.o2o.dao.split.DynamicDataSource">
        <property name="targetDataSources">
            <map>
                <entry value-ref="master" key="master">entry>
                <entry value-ref="slave" key="slave">entry>
            map>
        property>
    bean>

    <bean id="dataSourceDefault" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
        <property name="targetDataSource">
            <ref bean="dymicDataSources"/>
        property>
    bean>
    
    <bean id="dataSource" class="com.p6spy.engine.spy.P6DataSource">
        <constructor-arg>
            <ref bean="dataSourceDefault"/>
        constructor-arg>
    bean>

总结

    到这为止,实现主从同步以及代码层的读写分离,其实比较简单,遇到问题不要害怕,解决就行了

你可能感兴趣的:(——【项目实践】,——【Mybatis】,——【Spring】)