Mysql 读写分离的方案设计

Mysql读写分离的实现 读写分离可以发生在数据访问层、数据库连接层以及数据源。 {{ }} 一、数据访问层 即从数据库中获取业务层需要的数据,例如mapper。 在数据访问层实现读写分离需要建立两个数据库连接(读操作、写操作),主要依靠在dao中手动选择数据库的连接。 {{ }} 示例代码 优点:实现方便 缺点: 1. 侵入业务,每个数据操作都需要额...

Mysql读写分离的实现

读写分离可以发生在数据访问层、数据库连接层以及数据源。 示例图片

一、数据访问层

即从数据库中获取业务层需要的数据,例如mapper。 在数据访问层实现读写分离需要建立两个数据库连接(读操作、写操作),主要依靠在dao中手动选择数据库的连接。 示例图片

示例代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@Repository
public class DaoImpl implements DaoInterface {
    // 读数据库连接
    @Autowired
    private Jdbc readJdbc;

    // 写数据库连接
    @Autowired
    private Jdbc writeJdbc;

    @Override
    public boolean add(String appId, String name) {
        StringBuilder sql = new StringBuilder();
        sql.append("insert into sample(app_id, name, status, create_time)");
        sql.append(" values (?, ?, ?, ?) ");

        StatementParameter param = new StatementParameter();
        param.setString(appId);
        param.setString(name);
        param.setBool(true);
        param.setDate(new Date());

        return writeJdbc.insertForBoolean(sql.toString(), param);
    }

    @Override
    public Sample get(long appId) {
        StringBuilder sql = new StringBuilder();
        sql.append("select * from sample where app_id = ? ");

        StatementParameter param = new StatementParameter();
        param.setLong(appId);

        return readJdbc.query(sql.toString(), Sample.class, param);
    }

    @Override
    public Sample updateAndGet(String appId, boolean status) {
        StringBuilder writeSql = new StringBuilder();
        writeSql.append("update sample set status = ? where id = ? and app_id = ? ");

        StatementParameter writeParam = new StatementParameter();
        writeParam.setBool(status);
        writeParam.setString(appId);

        writeJdbc.updateForBoolean(writeSql.toString(), writeParam);

        StringBuilder readSql = new StringBuilder();
        readSql.append("select * from sample where app_id = ? ");

        StatementParameter readParam = new StatementParameter();
        readParam.setLong(appId);

        // 读写分离一致性,仍然需要采取写 JDBC 的方式进行读取,以防数据库还没有同步到主数据库
        // 传的数据
        return writeJdbc.query(readSql.toString(), Sample.class, readParam);
    }
}

优点:实现方便 缺点:

  1. 侵入业务,每个数据操作都需要额外考虑读写分离;
  2. 要求操作者自行实现读写窗口一致性,如果考虑不周就会导致数据读取失败。

二、数据库连接层

解析mapper的层,例如jdbc 示例图片

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class JdbcProxyImpl implements Jdbc {
    // 读/写 JDBC 实现
    private JdbcReaderImpl jdbcReaderImpl;
    private JdbcWriterImpl jdbcWriterImpl;

    public void setJdbcReaderImpl(JdbcReaderImpl jdbcReaderImpl) {
        this.jdbcReaderImpl = jdbcReaderImpl;
    }

    public void setJdbcWriterImpl(JdbcWriterImpl jdbcWriterImpl) {
        this.jdbcWriterImpl = jdbcWriterImpl;
    }

    // 更新的时候先需要标记为写入, 再调用写 JDBC 来实现更新
    @Override
    public int update(String sql) {
        ReadWriteDataSourceDecision.markWrite();
        return jdbcWriterImpl.update(sql);
    }

    // 在读取的时候先要判断当前线程下是否有写入操作, 如果有就直接使用写 JDBC 来读取, 否则才使用读 JDBC
    @Override
    public <T> T query(String sql, Class<T> elementType) {
        if (ReadWriteDataSourceDecision.isChoiceWrite()) {
            return jdbcWriterImpl.query(sql, elementType);
        }
        return jdbcReaderImpl.query(sql, elementType);
    }

    // 事务提交属于写入操作属性
    @Override
    public boolean commit() {
        return jdbcWriterImpl.commit();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class ReadWriteDataSourceDecision {
    public enum DataSourceType {
        write, read;
    }

    // 所有读写操作的标记会被记录在 ThreadLocal 这里, 线程是安全的
    private static final ThreadLocal<DataSourceType> holder = new ThreadLocal<DataSourceType>();

    public static void markWrite() {
        holder.set(DataSourceType.write);
    }

    public static void markRead() {
        holder.set(DataSourceType.read);
    }

    public static void reset() {
        holder.set(null);
    }

    public static boolean isChoiceNone() {
        return null == holder.get();
    }

    public static boolean isChoiceWrite() {
        return DataSourceType.write == holder.get();
    }

    public static boolean isChoiceRead() {
        return DataSourceType.read == holder.get();
    }
}

优点:

  1. 可实现读写窗口一致性切换;
  2. 独立组件,侵入性较低。

缺点:

  1. 读写分离的时候仍然需要额外配置两个读写数据源
  2. 对于主备复制时延较大的场景,仍然无法保障数据读取的一致性。

三、数据源

直接与数据库连接的部分,例如druid。 示例图片

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public enum MeoDsType {
    READ("read"),
    WRITE("write");

    private final String key;

    MeoDsType(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class RwDsContainer {
    private static final Map<MeoDsType, DataSource> container = new HashMap<>();

    public static DataSource get(MeoDsType type) {
        return container.get(type);
    }

    public static void put(MeoDsType type, DataSource dataSource) {
        container.put(type, dataSource);
    }

    public static boolean containsKey(MeoDsType type) {
        return container.containsKey(type);
    }
}
1
2
3
4
public interface DsDelayManager {
    void checkDsDelay() throws SQLException;  // 检查主从数据库是否存在延迟
    boolean isDelay();  // 返回当前是否存在延迟
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class RwDsManager {
    private final DsDelayManager delayManager = new MeoRwDsDelayManager();

    public void initDataSource(String[] urls, MeoDsType type) throws Exception {
        String dataSourceClass = getDataSourceClass();  // 示例数据源类
        Class<?> clazz = Class.forName(dataSourceClass);
        PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz).getPropertyDescriptors();

        for (String url : urls) {
            if (RwDsContainer.containsKey(type)) {
                return;
            }
            DataSource myds = (DataSource) clazz.getDeclaredConstructor().newInstance();
            for (PropertyDescriptor pd : pds) {
                if (getJdbcUrl().equals(pd.getName())) {
                    pd.getWriteMethod().invoke(myds, url);
                }

            }
            RwDsContainer.put(type, myds);
        }
    }

    private static String getJdbcUrl() {
        return "jdbcUrl";
    }

    private static String getDataSourceClass() {
        return "com.zaxxer.hikari.HikariDataSource";
    }

    public DataSource getReadDatasource() {
        return RwDsContainer.get(MeoDsType.READ);
    }

    public DataSource getWriteDatasource() {
        return RwDsContainer.get(MeoDsType.WRITE);
    }

    public Connection getReadConnection() throws SQLException {
        return getReadDatasource().getConnection();
    }

    public Connection getWriteConnection() throws SQLException {
        return getWriteDatasource().getConnection();
    }

    public Connection getReadConnection(String username, String password) throws SQLException {
        DataSource ds = getReadDatasource();
        if (username == null) {
            return ds.getConnection();
        } else {
            return ds.getConnection(username, password);
        }
    }

    public Connection getWriteConnection(String username, String password) throws SQLException {
        DataSource ds = getWriteDatasource();
        if (username == null) {
            return ds.getConnection();
        } else {
            return ds.getConnection(username, password);
        }
    }


    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        if (isReadRequest(sql) && !delayManager.isDelay()) {
            return getReadConnection().prepareStatement(sql, autoGeneratedKeys);
        } else {
            return getWriteConnection().prepareStatement(sql, autoGeneratedKeys);
        }
    }

    private boolean isReadRequest(String sql) {
        return sql.trim().toLowerCase().startsWith("select");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class MeoRwDsDelayManager implements DsDelayManager {
    private boolean isDelay;
    private static final int acceptDsDelayInMillis = 50;  // 主从同步容忍时间(毫秒)
    private final String updateSql = "UPDATE %s SET col = '%s'";
    private final String querySql = "SELECT col FROM %s";

    @Override
    public synchronized void checkDsDelay() throws SQLException {
        String uuid = UUID.randomUUID().toString();
        execute(String.format(updateSql, "test_table", uuid));  // 写入主库
        try {
            Thread.sleep(acceptDsDelayInMillis);  // 等待主从同步
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String qUuid = query(String.format(querySql, "test_table"));  // 从备库读取
        this.isDelay = !uuid.equals(qUuid);  // 判断是否延迟
    }

    @Override
    public boolean isDelay() {
        return this.isDelay;
    }

    // 执行数据库操作
    private void execute(String sql) {
        // 模拟执行写入主库逻辑(具体实现根据实际数据库库)
        System.out.println("Executing SQL on master: " + sql);
    }

    private String query(String sql) {
        // 模拟从从库查询(返回模拟数据)
        System.out.println("Querying SQL on slave: " + sql);
        return UUID.randomUUID().toString();  // 模拟延迟情况
    }
}
最后更新于 2025年01月19日
使用 Hugo 构建
主题 Stack 由 Jimmy 设计