ShardingConnection.java 7.6 KB
Newer Older
T
terrymanu 已提交
1
/*
T
terrymanu 已提交
2 3 4 5 6
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
T
terrymanu 已提交
7
 *
T
terrymanu 已提交
8
 *      http://www.apache.org/licenses/LICENSE-2.0
T
terrymanu 已提交
9
 *
T
terrymanu 已提交
10 11 12 13 14 15 16 17 18 19 20
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package com.dangdang.ddframe.rdb.sharding.jdbc;

import com.codahale.metrics.Timer.Context;
T
fix #95  
terrymanu 已提交
21
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
T
terrymanu 已提交
22 23
import com.dangdang.ddframe.rdb.sharding.jdbc.adapter.AbstractConnectionAdapter;
import com.dangdang.ddframe.rdb.sharding.metrics.MetricsContext;
T
terrymanu 已提交
24
import com.dangdang.ddframe.rdb.sharding.parser.result.router.SQLStatementType;
T
terrymanu 已提交
25
import com.google.common.base.Joiner;
26
import com.google.common.base.Optional;
G
fix #16  
gaohongtao 已提交
27 28 29
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
T
terrymanu 已提交
30

31
import javax.sql.DataSource;
T
terrymanu 已提交
32 33 34 35 36 37 38 39 40
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

T
terrymanu 已提交
41 42 43
/**
 * 支持分片的数据库连接.
 * 
T
terrymanu 已提交
44 45
 * @author zhangliang
 * @author gaohongtao
T
terrymanu 已提交
46
 */
G
fix #16  
gaohongtao 已提交
47
@RequiredArgsConstructor
T
terrymanu 已提交
48 49
public final class ShardingConnection extends AbstractConnectionAdapter {
    
G
fix #16  
gaohongtao 已提交
50
    @Getter(AccessLevel.PACKAGE)
T
terrymanu 已提交
51
    private final ShardingContext shardingContext;
T
terrymanu 已提交
52
    
T
terrymanu 已提交
53
    private final Map<String, Connection> connectionMap = new HashMap<>();
T
terrymanu 已提交
54 55 56 57 58
    
    /**
     * 根据数据源名称获取相应的数据库连接.
     * 
     * @param dataSourceName 数据源名称
T
terrymanu 已提交
59
     * @param sqlStatementType SQL语句类型
T
terrymanu 已提交
60 61
     * @return 数据库连接
     */
T
terrymanu 已提交
62 63
    public Connection getConnection(final String dataSourceName, final SQLStatementType sqlStatementType) throws SQLException {
        Connection result = getConnectionInternal(dataSourceName, sqlStatementType);
T
terrymanu 已提交
64 65
        replayMethodsInvocation(result);
        return result;
T
terrymanu 已提交
66 67 68 69
    }
    
    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
T
terrymanu 已提交
70
        return getConnection(shardingContext.getShardingRule().getDataSourceRule().getDataSourceNames().iterator().next(), SQLStatementType.SELECT).getMetaData();
T
terrymanu 已提交
71 72
    }
    
T
terrymanu 已提交
73
    private Connection getConnectionInternal(final String dataSourceName, final SQLStatementType sqlStatementType) throws SQLException {
74 75 76
        Optional<Connection> connectionOptional = fetchCachedConnectionBySqlStatementType(dataSourceName, sqlStatementType);
        if (connectionOptional.isPresent()) {
            return connectionOptional.get();
G
fix #16  
gaohongtao 已提交
77
        }
78 79
        Context metricsContext = MetricsContext.start(Joiner.on("-").join("ShardingConnection-getConnection", dataSourceName));
        DataSource dataSource = shardingContext.getShardingRule().getDataSourceRule().getDataSource(dataSourceName);
80
        String realDataSourceName = dataSourceName;
81 82
        if (dataSource instanceof MasterSlaveDataSource) {
            dataSource = ((MasterSlaveDataSource) dataSource).getDataSource(sqlStatementType);
83
            realDataSourceName = getRealDataSourceName(dataSourceName, sqlStatementType);
84 85
        }
        Connection result = dataSource.getConnection();
T
terrymanu 已提交
86
        MetricsContext.stop(metricsContext);
87
        connectionMap.put(realDataSourceName, result);
T
terrymanu 已提交
88
        return result;
T
terrymanu 已提交
89 90
    }
    
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    private String getRealDataSourceName(final String dataSourceName, final SQLStatementType sqlStatementType) {
        String slaveDataSourceName = getSlaveDataSourceName(dataSourceName);
        if (!MasterSlaveDataSource.isDML(sqlStatementType)) {
            return slaveDataSourceName;
        }
        Connection slaveConnection = connectionMap.remove(slaveDataSourceName);
        if (null != slaveConnection) {
            try {
                slaveConnection.close();
            } catch (final SQLException ignored) {
            }
        }
        return getMasterDataSourceName(dataSourceName);
    }
    
    private Optional<Connection> fetchCachedConnectionBySqlStatementType(final String dataSourceName, final SQLStatementType sqlStatementType) {
        if (connectionMap.containsKey(dataSourceName)) {
            return Optional.of(connectionMap.get(dataSourceName));
        }
        String masterDataSourceName = getMasterDataSourceName(dataSourceName);
        if (connectionMap.containsKey(masterDataSourceName)) {
            return Optional.of(connectionMap.get(masterDataSourceName));
        }
        if (MasterSlaveDataSource.isDML(sqlStatementType)) {
            return Optional.absent();
        }
        String slaveDataSourceName = getSlaveDataSourceName(dataSourceName);
        if (connectionMap.containsKey(slaveDataSourceName)) {
            return Optional.of(connectionMap.get(slaveDataSourceName));
        }
        return Optional.absent();
    }
    
    private String getMasterDataSourceName(final String dataSourceName) {
        return Joiner.on("-").join(dataSourceName, "SHARDING-JDBC", "MASTER");
    }
    
    private String getSlaveDataSourceName(final String dataSourceName) {
        return Joiner.on("-").join(dataSourceName, "SHARDING-JDBC", "SLAVE");
    }
    
T
terrymanu 已提交
132 133
    @Override
    public PreparedStatement prepareStatement(final String sql) throws SQLException {
G
fix #16  
gaohongtao 已提交
134
        return new ShardingPreparedStatement(this, sql);
T
terrymanu 已提交
135 136 137 138
    }
    
    @Override
    public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException {
G
fix #16  
gaohongtao 已提交
139
        return new ShardingPreparedStatement(this, sql, resultSetType, resultSetConcurrency);
T
terrymanu 已提交
140 141 142 143
    }
    
    @Override
    public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException {
G
fix #16  
gaohongtao 已提交
144
        return new ShardingPreparedStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability);
T
terrymanu 已提交
145 146 147 148
    }
    
    @Override
    public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException {
G
fix #16  
gaohongtao 已提交
149
        return new ShardingPreparedStatement(this, sql, autoGeneratedKeys);
T
terrymanu 已提交
150 151 152 153
    }
    
    @Override
    public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) throws SQLException {
G
fix #16  
gaohongtao 已提交
154
        return new ShardingPreparedStatement(this, sql, columnIndexes);
T
terrymanu 已提交
155 156 157 158
    }
    
    @Override
    public PreparedStatement prepareStatement(final String sql, final String[] columnNames) throws SQLException {
G
fix #16  
gaohongtao 已提交
159
        return new ShardingPreparedStatement(this, sql, columnNames);
T
terrymanu 已提交
160 161 162 163
    }
    
    @Override
    public Statement createStatement() throws SQLException {
G
fix #16  
gaohongtao 已提交
164
        return new ShardingStatement(this);
T
terrymanu 已提交
165 166 167 168
    }
    
    @Override
    public Statement createStatement(final int resultSetType, final int resultSetConcurrency) throws SQLException {
G
fix #16  
gaohongtao 已提交
169
        return new ShardingStatement(this, resultSetType, resultSetConcurrency);
T
terrymanu 已提交
170 171 172 173
    }
    
    @Override
    public Statement createStatement(final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException {
G
fix #16  
gaohongtao 已提交
174
        return new ShardingStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability);
T
terrymanu 已提交
175 176 177 178 179 180
    }
    
    @Override
    public Collection<Connection> getConnections() {
        return connectionMap.values();
    }
T
fix #95  
terrymanu 已提交
181 182 183 184 185 186 187
    
    @Override
    public void close() throws SQLException {
        super.close();
        HintManagerHolder.clear();
        MasterSlaveDataSource.resetDMLFlag();
    }
T
terrymanu 已提交
188
}