国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring 實現數據庫讀寫分離的示例

Spring 實現數據庫讀寫分離的示例

2020-07-23 11:50濤叔 Java教程

現在大型的電子商務系統,在數據庫層面大都采用讀寫分離技術,我們通常的做法就是把查詢從主庫中抽取出來,采用多個從庫,使用負載均衡,減輕每個從庫的查詢壓力。

現在大型的電子商務系統,在數據庫層面大都采用讀寫分離技術,就是一個Master數據庫,多個Slave數據庫。Master庫負責數據更新和實時數據查詢,Slave庫當然負責非實時數據查詢。因為在實際的應用中,數據庫都是讀多寫少(讀取數據的頻率高,更新數據的頻率相對較少),而讀取數據通常耗時比較長,占用數據庫服務器的CPU較多,從而影響用戶體驗。我們通常的做法就是把查詢從主庫中抽取出來,采用多個從庫,使用負載均衡,減輕每個從庫的查詢壓力。

采用讀寫分離技術的目標:有效減輕Master庫的壓力,又可以把用戶查詢數據的請求分發到不同的Slave庫,從而保證系統的健壯性。我們看下采用讀寫分離的背景。

隨著網站的業務不斷擴展,數據不斷增加,用戶越來越多,數據庫的壓力也就越來越大,采用傳統的方式,比如:數據庫或者SQL的優化基本已達不到要求,這個時候可以采用讀寫分離的策 略來改變現狀。

具體到開發中,如何方便的實現讀寫分離呢?目前常用的有兩種方式:

1 第一種方式是我們最常用的方式,就是定義2個數據庫連接,一個是MasterDataSource,另一個是SlaveDataSource。更新數據時我們讀取MasterDataSource,查詢數據時我們讀取SlaveDataSource。這種方式很簡單,我就不贅述了。

2 第二種方式動態數據源切換,就是在程序運行時,把數據源動態織入到程序中,從而選擇讀取主庫還是從庫。主要使用的技術是:annotation,Spring AOP ,反射。下面會詳細的介紹實現方式。

在介紹實現方式之前,我們先準備一些必要的知識,spring 的AbstractRoutingDataSource 類

AbstractRoutingDataSource這個類 是spring2.0以后增加的,我們先來看下AbstractRoutingDataSource的定義:

 

復制代碼 代碼如下:

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}

 

AbstractRoutingDataSource繼承了AbstractDataSource ,而AbstractDataSource 又是DataSource 的子類。DataSource 是javax.sql 的數據源接口,定義如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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個方法,都是獲取數據庫連接。我們在看下AbstractRoutingDataSource 如何實現了DataSource接口:

?
1
2
3
4
5
6
7
public Connection getConnection() throws SQLException {
    return determineTargetDataSource().getConnection();
  }
 
  public Connection getConnection(String username, String password) throws SQLException {
    return determineTargetDataSource().getConnection(username, password);
  }

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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;
  }

我們最關心的還是下面2句話:

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

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

?
1
2
3
private Map<Object, DataSource> resolvedDataSources;
 
protected abstract Object determineCurrentLookupKey()

看到以上定義,我們是不是有點思路了,resolvedDataSources是Map類型,我們可以把MasterDataSource和SlaveDataSource存到Map中,如下:

key  value
master MasterDataSource
slave SlaveDataSource

我們在寫一個類DynamicDataSource 繼承AbstractRoutingDataSource,實現其determineCurrentLookupKey() 方法,該方法返回Map的key,master或slave。

好了,說了這么多,有點煩了,下面我們看下怎么實現。

上面已經提到了我們要使用的技術,我們先看下annotation的定義:

?
1
2
3
4
5
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
  String value();
}

我們還需要實現spring的抽象類AbstractRoutingDataSource,就是實現determineCurrentLookupKey方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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()值,我們需要在程序運行時調用DynamicDataSourceHolder.putDataSource()方法,對其賦值。下面是我們實現的核心部分,也就是AOP部分,DataSourceAspect定義如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
    }
  }
}

為了方便測試,我定義了2個數據庫,shop模擬Master庫,test模擬Slave庫,shop和test的表結構一致,但數據不同,數據庫配置如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<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配置

?
1
2
3
4
5
6
7
8
9
10
<!-- 配置數據庫注解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>
  <!-- 配置數據庫注解aop -->

下面是MyBatis的UserMapper的定義,為了方便測試,登錄讀取的是Master庫,用戶列表讀取Slave庫:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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();
} 

好了,運行我們的Eclipse看看效果,輸入用戶名admin 登錄看看效果

Spring 實現數據庫讀寫分離的示例

Spring 實現數據庫讀寫分離的示例以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/surge/p/3582248.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品免费av| 在线观看成人 | 国产剧情一区二区 | 黑人xxx视频 | 欧美影 | 亚洲a网| 91在线视频 | 久久久九色 | 久久久久久91亚洲精品中文字幕 | 成人免费xxx在线观看 | 日美毛片 | 国产a自拍| 成人av免费 | 国产精品高潮呻吟久久 | 色婷婷精品国产一区二区三区 | 玖玖精品在线 | av网址aaa | 久久久99精品免费观看 | www.伊人网| 国产一区二区三区免费 | 欧美日韩视频在线第一区 | 久久久久久高清 | 99亚洲精品 | 精品国产一区二区三区免费 | 日本成人黄色网址 | 久久精品国产一区二区三区不卡 | 欧州一级片 | 国产一区二区精品 | 色网站在线| 久久久精品免费视频 | 国产福利一区二区 | 激情综合网激情 | 欧洲免费视频 | 视频一区 中文字幕 | 性欧美久久久 | 一本大道综合伊人精品热热 | 欧美国产精品一区 | 国产欧美在线 | 国产精品久久一区 | www.国产精品 | 一区久久|