OrchestrationMasterSlaveDataSourceFactory.java 6.9 KB
Newer Older
T
terrymanu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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>
 */

18
package io.shardingjdbc.orchestration.api;
T
terrymanu 已提交
19

H
haocao 已提交
20
import com.google.common.base.Charsets;
21 22 23
import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration;
import io.shardingjdbc.core.jdbc.core.datasource.MasterSlaveDataSource;
H
haocao 已提交
24
import io.shardingjdbc.orchestration.instance.InstanceNode;
H
haocao 已提交
25
import io.shardingjdbc.orchestration.jdbc.datasource.CircuitBreakerDataSource;
26 27 28
import io.shardingjdbc.orchestration.json.DataSourceJsonConverter;
import io.shardingjdbc.orchestration.json.GsonFactory;
import io.shardingjdbc.orchestration.reg.base.CoordinatorRegistryCenter;
T
terrymanu 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;

/**
 * Orchestration master slave data source factory.
 * 
 * @author zhangliang 
H
haocao 已提交
45
 * @author caohao  
T
terrymanu 已提交
46 47 48 49 50 51
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class OrchestrationMasterSlaveDataSourceFactory {
    
    /**
     * Create sharding data source.
H
haocao 已提交
52 53
     *
     * @param config orchestration master slave configuration
T
terrymanu 已提交
54 55 56
     * @return sharding data source
     * @throws SQLException SQL exception
     */
H
haocao 已提交
57 58 59 60 61
    public static DataSource createDataSource(final OrchestrationMasterSlaveConfiguration config) throws SQLException {
        initRegistryCenter(config);
        MasterSlaveDataSource result = (MasterSlaveDataSource) MasterSlaveDataSourceFactory.createDataSource(config.getDataSourceMap(), config.getMasterSlaveRuleConfiguration());
        addConfigurationChangeListener(config.getName(), config.getRegistryCenter(), result);
        addInstancesStateChangeListener(config.getName(), config.getRegistryCenter(), result);
T
terrymanu 已提交
62 63 64
        return result;
    }
    
H
haocao 已提交
65 66 67
    private static void initRegistryCenter(final OrchestrationMasterSlaveConfiguration config) throws SQLException {
        String name = config.getName();
        CoordinatorRegistryCenter registryCenter = config.getRegistryCenter();
T
terrymanu 已提交
68
        registryCenter.init();
H
haocao 已提交
69
        persist(config);
H
haocao 已提交
70
        registryCenter.persistEphemeral("/" + name + "/state/instances/" + new InstanceNode().getInstanceId(), "");
T
terrymanu 已提交
71 72 73
        registryCenter.addCacheData("/" + name + "/config");
    }
    
H
haocao 已提交
74 75 76 77 78 79
    private static void persist(final OrchestrationMasterSlaveConfiguration config) throws SQLException {
        String name = config.getName();
        CoordinatorRegistryCenter registryCenter = config.getRegistryCenter();
        if (config.isOverwrite() || registryCenter.getChildrenKeys("/" + name + "/config").isEmpty()) {
            registryCenter.persist("/" + name + "/config/datasource", DataSourceJsonConverter.toJson(config.getDataSourceMap()));
            registryCenter.persist("/" + name + "/config/masterslave", GsonFactory.getGson().toJson(config.getMasterSlaveRuleConfiguration()));
H
haocao 已提交
80 81 82
        }
    }
    
T
terrymanu 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    private static void addConfigurationChangeListener(final String name, final CoordinatorRegistryCenter registryCenter, final MasterSlaveDataSource masterSlaveDataSource) {
        TreeCache cache = (TreeCache) registryCenter.getRawCache("/" + name + "/config");
        cache.getListenable().addListener(new TreeCacheListener() {
            
            @Override
            public void childEvent(final CuratorFramework client, final TreeCacheEvent event) throws Exception {
                ChildData childData = event.getData();
                if (null == childData || null == childData.getData()) {
                    return;
                }
                String path = childData.getPath();
                if (path.isEmpty()) {
                    return;
                }
                if (("/" + name + "/config/datasource").equals(path)) {
                    Map<String, DataSource> newDataSourceMap = DataSourceJsonConverter.fromJson(new String(childData.getData(), Charsets.UTF_8));
T
terrymanu 已提交
99
                    MasterSlaveRuleConfiguration masterSlaveRuleConfig = GsonFactory.getGson().fromJson(registryCenter.get("/" + name + "/config/masterslave"), MasterSlaveRuleConfiguration.class);
T
terrymanu 已提交
100 101
                    masterSlaveDataSource.renew(masterSlaveRuleConfig.build(newDataSourceMap));
                } else if (("/" + name + "/config/masterslave").equals(path)) {
T
terrymanu 已提交
102
                    MasterSlaveRuleConfiguration newMasterSlaveRuleConfig = GsonFactory.getGson().fromJson(new String(childData.getData(), Charsets.UTF_8), MasterSlaveRuleConfiguration.class);
T
terrymanu 已提交
103 104 105 106 107 108
                    Map<String, DataSource> dataSourceMap = DataSourceJsonConverter.fromJson(registryCenter.get("/" + name + "/config/datasource"));
                    masterSlaveDataSource.renew(newMasterSlaveRuleConfig.build(dataSourceMap));
                }
            }
        });
    }
H
haocao 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    
    private static void addInstancesStateChangeListener(final String name, final CoordinatorRegistryCenter registryCenter, final MasterSlaveDataSource masterSlaveDataSource) {
        TreeCache cache = (TreeCache) registryCenter.getRawCache("/" + name + "/state/instances");
        cache.getListenable().addListener(new TreeCacheListener() {
            
            @Override
            public void childEvent(final CuratorFramework client, final TreeCacheEvent event) throws Exception {
                ChildData childData = event.getData();
                if (null == childData || null == childData.getData()) {
                    return;
                }
                String path = childData.getPath();
                if (path.isEmpty() || !"disabled".equals(registryCenter.get(path))) {
                    return;
                }
                MasterSlaveRuleConfiguration masterSlaveRuleConfig = GsonFactory.getGson().fromJson(new String(childData.getData(), Charsets.UTF_8), MasterSlaveRuleConfiguration.class);
                Map<String, DataSource> dataSourceMap = DataSourceJsonConverter.fromJson(registryCenter.get("/" + name + "/config/datasource"));
                for (String each : dataSourceMap.keySet()) {
H
haocao 已提交
127
                    dataSourceMap.put(each, new CircuitBreakerDataSource());
H
haocao 已提交
128 129 130 131 132
                }
                masterSlaveDataSource.renew(masterSlaveRuleConfig.build(dataSourceMap));
            }
        });
    }
T
terrymanu 已提交
133
}