Java tutorial
/* * Copyright 2009-2012 the original author or authors. * * 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 i 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. */ package com.gzj.tulip.jade.dataaccess.datasource; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.sql.DataSource; import com.gzj.tulip.jade.dataaccess.DataSourceHolder; import com.gzj.tulip.jade.annotation.SQLType; import com.gzj.tulip.jade.dataaccess.DataSourceFactory; import com.gzj.tulip.jade.statement.StatementMetaData; import org.springframework.util.CollectionUtils; /** * master-slave?????master?slave * <p> * * Java?Spring?????) * * <pre> * MasterSlaveDataSourceFactory mainFactory = new MasterSlaveDataSourceFactory(); * * DataSource master = getMasterDataSource(); * mainFactory.setMasters(new SimpleDataSourceFactory(master)); * * List<DataSource> slaves = getSlaveDataSources(); * if (queryFromMaster) { * slaves = new ArrayList<DataSource>(slaves); * slaves.add(master); * } * mainFactory.setSlaves(new RandomDataSourceFactory(slaves)); * </pre> * * @author [qieqie.wang@gmail.com] * */ public class MasterSlaveDataSourceFactory implements DataSourceFactory { private DataSourceFactory masters = new RandomDataSourceFactory(); private DataSourceFactory slaves = new RandomDataSourceFactory(); public MasterSlaveDataSourceFactory() { } /** * * @param master * @param slaves * @param queryFromMaster true?master??? */ public MasterSlaveDataSourceFactory(DataSource master, List<DataSource> slaves, boolean queryFromMaster) { if (queryFromMaster && !CollectionUtils.containsInstance(slaves, master)) { slaves = new ArrayList<DataSource>(slaves); slaves.add(master); } setSlaves(new RandomDataSourceFactory(slaves)); setMasters(new SimpleDataSourceFactory(master)); } //------------------ /** * * @param masters * @see RandomDataSourceFactory * @see SimpleDataSourceFactory */ public void setMasters(DataSourceFactory masters) { this.masters = masters; } /** * * @param slaves * @see RandomDataSourceFactory */ public void setSlaves(DataSourceFactory slaves) { this.slaves = slaves; } @Override public DataSourceHolder getHolder(StatementMetaData metaData, Map<String, Object> runtimeProperties) { if (metaData.getSQLType() != SQLType.READ) { return masters.getHolder(metaData, runtimeProperties); } else { return slaves.getHolder(metaData, runtimeProperties); } } }