当单机数据库遇到瓶颈后,我们最常见的就是读写分离和主从同步,那么当再遇到瓶颈后怎么办呢?我们的解决办法就是垂直拆分。
一、什么是垂直拆分
数据的切分(Sharding)根据其切分规则的类型,可以分为两种切分模式。垂直拆分就是把一个数据库的不同业务单元的数据分到不同数据库中。
二、优缺点
优点:
拆分后业务清晰,拆分规则明确。
系统之间整合或扩展容易。
数据维护简单。
缺点:
部分业务表无法join,只能通过接口方式解决,提高了系统复杂度。
受每种业务不同的限制存在单库性能瓶颈,不易数据扩展跟性能提高。
事务处理复杂。
由于垂直切分是按照业务的分类将表分散到不同的库,所以有些业务表会过于庞大,存在单库读写与存储瓶颈,所以就需要水平
拆分来做解决。
三、实现方式
数据库的拆分有很多中间件都可以实现,如mycat,这里我们介绍一种比较方便的由Spring提供的方式。强大的Spring已经为我们提供了AbstractRoutingDataSource这个类做支持。
实现数据源切换的功能就是自定义一个类扩展AbstractRoutingDataSource抽象类,其实该相当于数据源DataSourcer的路由中介,可以实现在项目运行时根据相应key值切换到对应的数据源DataSource上。先看看AbstractRoutingDataSource的源码:
/*
* Copyright 2002-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 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.
*/
package org.springframework.jdbc.datasource.lookup;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.util.Assert;
/**
* Abstract {@link javax.sql.DataSource} implementation that routes {@link #getConnection()}
* calls to one of various target DataSources based on a lookup key. The latter is usually
* (but not necessarily) determined through some thread-bound transaction context.
*
* @author Juergen Hoeller
* @since 2.0.1
* @se