国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

Spring 實(shí)現(xiàn)數(shù)據(jù)庫(kù)讀寫(xiě)分離的示例

2019-11-26 13:18:55
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

現(xiàn)在大型的電子商務(wù)系統(tǒng),在數(shù)據(jù)庫(kù)層面大都采用讀寫(xiě)分離技術(shù),就是一個(gè)Master數(shù)據(jù)庫(kù),多個(gè)Slave數(shù)據(jù)庫(kù)。Master庫(kù)負(fù)責(zé)數(shù)據(jù)更新和實(shí)時(shí)數(shù)據(jù)查詢(xún),Slave庫(kù)當(dāng)然負(fù)責(zé)非實(shí)時(shí)數(shù)據(jù)查詢(xún)。因?yàn)樵趯?shí)際的應(yīng)用中,數(shù)據(jù)庫(kù)都是讀多寫(xiě)少(讀取數(shù)據(jù)的頻率高,更新數(shù)據(jù)的頻率相對(duì)較少),而讀取數(shù)據(jù)通常耗時(shí)比較長(zhǎng),占用數(shù)據(jù)庫(kù)服務(wù)器的CPU較多,從而影響用戶(hù)體驗(yàn)。我們通常的做法就是把查詢(xún)從主庫(kù)中抽取出來(lái),采用多個(gè)從庫(kù),使用負(fù)載均衡,減輕每個(gè)從庫(kù)的查詢(xún)壓力。

采用讀寫(xiě)分離技術(shù)的目標(biāo):有效減輕Master庫(kù)的壓力,又可以把用戶(hù)查詢(xún)數(shù)據(jù)的請(qǐng)求分發(fā)到不同的Slave庫(kù),從而保證系統(tǒng)的健壯性。我們看下采用讀寫(xiě)分離的背景。

隨著網(wǎng)站的業(yè)務(wù)不斷擴(kuò)展,數(shù)據(jù)不斷增加,用戶(hù)越來(lái)越多,數(shù)據(jù)庫(kù)的壓力也就越來(lái)越大,采用傳統(tǒng)的方式,比如:數(shù)據(jù)庫(kù)或者SQL的優(yōu)化基本已達(dá)不到要求,這個(gè)時(shí)候可以采用讀寫(xiě)分離的策 略來(lái)改變現(xiàn)狀。

具體到開(kāi)發(fā)中,如何方便的實(shí)現(xiàn)讀寫(xiě)分離呢?目前常用的有兩種方式:

1 第一種方式是我們最常用的方式,就是定義2個(gè)數(shù)據(jù)庫(kù)連接,一個(gè)是MasterDataSource,另一個(gè)是SlaveDataSource。更新數(shù)據(jù)時(shí)我們讀取MasterDataSource,查詢(xún)數(shù)據(jù)時(shí)我們讀取SlaveDataSource。這種方式很簡(jiǎn)單,我就不贅述了。

2 第二種方式動(dòng)態(tài)數(shù)據(jù)源切換,就是在程序運(yùn)行時(shí),把數(shù)據(jù)源動(dòng)態(tài)織入到程序中,從而選擇讀取主庫(kù)還是從庫(kù)。主要使用的技術(shù)是:annotation,Spring AOP ,反射。下面會(huì)詳細(xì)的介紹實(shí)現(xiàn)方式。

在介紹實(shí)現(xiàn)方式之前,我們先準(zhǔn)備一些必要的知識(shí),spring 的AbstractRoutingDataSource 類(lèi)

AbstractRoutingDataSource這個(gè)類(lèi) 是spring2.0以后增加的,我們先來(lái)看下AbstractRoutingDataSource的定義:

復(fù)制代碼 代碼如下:

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}

AbstractRoutingDataSource繼承了AbstractDataSource ,而AbstractDataSource 又是DataSource 的子類(lèi)。DataSource 是javax.sql 的數(shù)據(jù)源接口,定義如下:

public interface DataSource extends CommonDataSource,Wrapper { /**  * <p>Attempts to establish a connection with the data source that  * this <code>DataSource</code> object represents.  *  * @return a connection to the data source  * @exception SQLException if a database access error occurs  */ Connection getConnection() throws SQLException; /**  * <p>Attempts to establish a connection with the data source that  * this <code>DataSource</code> object represents.  *  * @param username the database user on whose behalf the connection is  * being made  * @param password the user's password  * @return a connection to the data source  * @exception SQLException if a database access error occurs  * @since 1.4  */ Connection getConnection(String username, String password)  throws SQLException;}

DataSource 接口定義了2個(gè)方法,都是獲取數(shù)據(jù)庫(kù)連接。我們?cè)诳聪翧bstractRoutingDataSource 如何實(shí)現(xiàn)了DataSource接口:

public Connection getConnection() throws SQLException {    return determineTargetDataSource().getConnection();  }  public Connection getConnection(String username, String password) throws SQLException {    return determineTargetDataSource().getConnection(username, password);  }

很顯然就是調(diào)用自己的determineTargetDataSource() 方法獲取到connection。determineTargetDataSource方法定義如下:

protected DataSource determineTargetDataSource() {    Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");    Object lookupKey = determineCurrentLookupKey();    DataSource dataSource = this.resolvedDataSources.get(lookupKey);    if (dataSource == null && (this.lenientFallback || lookupKey == null)) {      dataSource = this.resolvedDefaultDataSource;    }    if (dataSource == null) {      throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");    }    return dataSource;  }

我們最關(guān)心的還是下面2句話:

Object lookupKey = determineCurrentLookupKey();DataSource dataSource = this.resolvedDataSources.get(lookupKey);

determineCurrentLookupKey方法返回lookupKey,resolvedDataSources方法就是根據(jù)lookupKey從Map中獲得數(shù)據(jù)源。resolvedDataSources 和determineCurrentLookupKey定義如下:

  private Map<Object, DataSource> resolvedDataSources;  protected abstract Object determineCurrentLookupKey()

看到以上定義,我們是不是有點(diǎn)思路了,resolvedDataSources是Map類(lèi)型,我們可以把MasterDataSource和SlaveDataSource存到Map中,如下:

key  value
master MasterDataSource
slave SlaveDataSource

我們?cè)趯?xiě)一個(gè)類(lèi)DynamicDataSource 繼承AbstractRoutingDataSource,實(shí)現(xiàn)其determineCurrentLookupKey() 方法,該方法返回Map的key,master或slave。

好了,說(shuō)了這么多,有點(diǎn)煩了,下面我們看下怎么實(shí)現(xiàn)。

上面已經(jīng)提到了我們要使用的技術(shù),我們先看下annotation的定義:

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface DataSource {  String value();}

我們還需要實(shí)現(xiàn)spring的抽象類(lèi)AbstractRoutingDataSource,就是實(shí)現(xiàn)determineCurrentLookupKey方法:

public class DynamicDataSource extends AbstractRoutingDataSource {  @Override  protected Object determineCurrentLookupKey() {    // TODO Auto-generated method stub    return DynamicDataSourceHolder.getDataSouce();  }}public class DynamicDataSourceHolder {  public static final ThreadLocal<String> holder = new ThreadLocal<String>();  public static void putDataSource(String name) {    holder.set(name);  }  public static String getDataSouce() {    return holder.get();  }}

從DynamicDataSource 的定義看出,他返回的是DynamicDataSourceHolder.getDataSouce()值,我們需要在程序運(yùn)行時(shí)調(diào)用DynamicDataSourceHolder.putDataSource()方法,對(duì)其賦值。下面是我們實(shí)現(xiàn)的核心部分,也就是AOP部分,DataSourceAspect定義如下:

public class DataSourceAspect {  public void before(JoinPoint point)  {    Object target = point.getTarget();    String method = point.getSignature().getName();    Class<?>[] classz = target.getClass().getInterfaces();    Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())        .getMethod().getParameterTypes();    try {      Method m = classz[0].getMethod(method, parameterTypes);      if (m != null && m.isAnnotationPresent(DataSource.class)) {        DataSource data = m            .getAnnotation(DataSource.class);        DynamicDataSourceHolder.putDataSource(data.value());        System.out.println(data.value());      }          } catch (Exception e) {      // TODO: handle exception    }  }}

為了方便測(cè)試,我定義了2個(gè)數(shù)據(jù)庫(kù),shop模擬Master庫(kù),test模擬Slave庫(kù),shop和test的表結(jié)構(gòu)一致,但數(shù)據(jù)不同,數(shù)據(jù)庫(kù)配置如下:

<bean id="masterdataSource"    class="org.springframework.jdbc.datasource.DriverManagerDataSource">    <property name="driverClassName" value="com.mysql.jdbc.Driver" />    <property name="url" value="jdbc:mysql://127.0.0.1:3306/shop" />    <property name="username" value="root" />    <property name="password" value="yangyanping0615" />  </bean>  <bean id="slavedataSource"    class="org.springframework.jdbc.datasource.DriverManagerDataSource">    <property name="driverClassName" value="com.mysql.jdbc.Driver" />    <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />    <property name="username" value="root" />    <property name="password" value="yangyanping0615" />  </bean>      <beans:bean id="dataSource" class="com.air.shop.common.db.DynamicDataSource">    <property name="targetDataSources">        <map key-type="java.lang.String">          <!-- write -->         <entry key="master" value-ref="masterdataSource"/>          <!-- read -->         <entry key="slave" value-ref="slavedataSource"/>        </map>            </property>     <property name="defaultTargetDataSource" ref="masterdataSource"/>   </beans:bean>  <bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource" />  </bean>  <!-- 配置SqlSessionFactoryBean -->  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dataSource" />    <property name="configLocation" value="classpath:config/mybatis-config.xml" />  </bean>

在spring的配置中增加aop配置

<!-- 配置數(shù)據(jù)庫(kù)注解aop -->  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>  <beans:bean id="manyDataSourceAspect" class="com.air.shop.proxy.DataSourceAspect" />  <aop:config>    <aop:aspect id="c" ref="manyDataSourceAspect">      <aop:pointcut id="tx" expression="execution(* com.air.shop.mapper.*.*(..))"/>      <aop:before pointcut-ref="tx" method="before"/>    </aop:aspect>  </aop:config>  <!-- 配置數(shù)據(jù)庫(kù)注解aop -->

下面是MyBatis的UserMapper的定義,為了方便測(cè)試,登錄讀取的是Master庫(kù),用戶(hù)列表讀取Slave庫(kù):

public interface UserMapper {  @DataSource("master")  public void add(User user);  @DataSource("master")  public void update(User user);  @DataSource("master")  public void delete(int id);  @DataSource("slave")  public User loadbyid(int id);  @DataSource("master")  public User loadbyname(String name);    @DataSource("slave")  public List<User> list();} 

好了,運(yùn)行我們的Eclipse看看效果,輸入用戶(hù)名admin 登錄看看效果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 阆中市| 新宾| 石屏县| 绿春县| 汉源县| 泰来县| 吴堡县| 望奎县| 美姑县| 正宁县| 永吉县| 固始县| 济源市| 佳木斯市| 肇源县| 眉山市| 丰原市| 祁阳县| 宁海县| 平陆县| 浦县| 临泉县| 临清市| 新津县| 云林县| 临洮县| 都江堰市| 旺苍县| 邛崃市| 兖州市| 驻马店市| 太保市| 息烽县| 辽中县| 澜沧| 漯河市| 衡山县| 彭州市| 应城市| 正阳县| 正镶白旗|