一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

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

服務(wù)器之家 - 編程語言 - Java教程 - Spring 實現(xiàn)數(shù)據(jù)庫讀寫分離的示例

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

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

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

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

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

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

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

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

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

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

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

 

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

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}

 

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

?
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個方法,都是獲取數(shù)據(jù)庫連接。我們在看下AbstractRoutingDataSource 如何實現(xiàn)了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);
  }

很顯然就是調(diào)用自己的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;
  }

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

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

determineCurrentLookupKey方法返回lookupKey,resolvedDataSources方法就是根據(jù)lookupKey從Map中獲得數(shù)據(jù)源。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,實現(xiàn)其determineCurrentLookupKey() 方法,該方法返回Map的key,master或slave。

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

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

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

我們還需要實現(xiàn)spring的抽象類AbstractRoutingDataSource,就是實現(xiàn)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()值,我們需要在程序運行時調(diào)用DynamicDataSourceHolder.putDataSource()方法,對其賦值。下面是我們實現(xiàn)的核心部分,也就是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個數(shù)據(jù)庫,shop模擬Master庫,test模擬Slave庫,shop和test的表結(jié)構(gòu)一致,但數(shù)據(jù)不同,數(shù)據(jù)庫配置如下:

?
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
<!-- 配置數(shù)據(jù)庫注解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ù)庫注解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 實現(xiàn)數(shù)據(jù)庫讀寫分離的示例

Spring 實現(xiàn)數(shù)據(jù)庫讀寫分離的示例以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 学校女性奴sm训练调教 | 日本一区二区精品88 | 手机在线观看国产精选免费 | 国产精品模特hd在线 | 男女性潮高片无遮挡禁18 | 婷婷伊人综合亚洲综合网 | 成人性色生活片免费网 | 精品国产人妻国语 | 亚洲、国产综合视频 | 男男浴室吸乳play | 国产激情视频网站 | 深夜视频免费看 | 欧美色精品天天在线观看视频 | 男生和女生艹逼 | 欧美视频在线一区 | 成人国产午夜在线视频 | 日本精品中文字幕在线播放 | 俄罗斯13一14处出血视频在线 | 国产欧美精品一区二区三区 | 午夜视频一区二区三区 | 日本中文字幕在线观看视频 | 欧美成人tv在线观看免费 | 大陆国产vs国产对白 | 日本艳鉧动漫1~6完整版在 | 人妇小说 | 男人女人日皮 | 女人是男人的未来1分49分 | 色花堂中文字幕98堂网址 | 国产日韩一区二区三区 | 手机看片国产免费现在观看 | 国产性片在线观看 | 国产精品激情综合久久 | 91最新国产 | 免费看片黄 | 手机在线观看国产精选免费 | 午夜一区二区三区 | 男生和女生搞逼逼 | 亚洲成人网在线 | 福利片福利一区二区三区 | 扒开放荡老师裙子猛烈的进入 | 免费看国产一级特黄aa大片 |