Spring 配置多數據源實現數據庫讀寫分離

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

 

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

 

  隨着網站的業務不斷擴展,數據不斷增長,用戶愈來愈多,數據庫的壓力也就愈來愈大,採用傳統的方式,好比:數據庫或者SQL的優化基本已達不到要求,這個時候能夠採用讀寫分離的策 略來改變現狀。java

 

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

 

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

 

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

 

   在介紹實現方式以前,咱們先準備一些必要的知識,spring 的AbstractRoutingDataSource 類數據庫

 

     AbstractRoutingDataSource這個類 是spring2.0之後增長的,咱們先來看下AbstractRoutingDataSource的定義:express

Java代碼 服務器

 收藏代碼

  1. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean  {}  

 

Java代碼 session

 收藏代碼

  1. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {  
  2.   
  3.     private Map<Object, Object> targetDataSources;  
  4.   
  5.     private Object defaultTargetDataSource;  
  6.   
  7.     private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();  
  8.   
  9.     private Map<Object, DataSource> resolvedDataSources;  
  10.   
  11.     private DataSource resolvedDefaultDataSource;  

 

    AbstractRoutingDataSource繼承了AbstractDataSource ,而AbstractDataSource 又是DataSource 的子類。

DataSource   是javax.sql 的數據源接口,定義以下:

Java代碼 

 收藏代碼

  1. public interface DataSource  extends CommonDataSource,Wrapper {  
  2.   
  3.   Connection getConnection() throws SQLException;  
  4.    
  5.   Connection getConnection(String username, String password)  
  6.     throws SQLException;  
  7. }  

 DataSource 接口定義了2個方法,都是獲取數據庫鏈接。咱們在看下AbstractRoutingDataSource 如何實現了DataSource接口:

 

Java代碼 

 收藏代碼

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

 很顯然就是調用本身的determineTargetDataSource()  方法獲取到connection。determineTargetDataSource方法定義以下:

 

Java代碼 

 收藏代碼

  1. protected DataSource determineTargetDataSource() {  
  2.         Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");  
  3.         Object lookupKey = determineCurrentLookupKey();  
  4.         DataSource dataSource = this.resolvedDataSources.get(lookupKey);  
  5.         if (dataSource == null && (this.lenientFallback || lookupKey == null)) {  
  6.             dataSource = this.resolvedDefaultDataSource;  
  7.         }  
  8.         if (dataSource == null) {  
  9.             throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");  
  10.         }  
  11.         return dataSource;  
  12.     }  

 

咱們最關心的仍是下面2句話:

  Object lookupKey = determineCurrentLookupKey();

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

 

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

 

  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的定義:

Java代碼 

 收藏代碼

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

 

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

Java代碼 

 收藏代碼

  1. public class DynamicDataSource extends AbstractRoutingDataSource {  
  2.   
  3.     @Override  
  4.     protected Object determineCurrentLookupKey() {  
  5.         // TODO Auto-generated method stub  
  6.         return DynamicDataSourceHolder.getDataSouce();  
  7.     }  
  8.   
  9. }  
  10.   
  11.   
  12. public class DynamicDataSourceHolder {  
  13.     public static final ThreadLocal<String> holder = new ThreadLocal<String>();  
  14.   
  15.     public static void putDataSource(String name) {  
  16.         holder.set(name);  
  17.     }  
  18.   
  19.     public static String getDataSouce() {  
  20.         return holder.get();  
  21.     }  
  22. }  

 

    從DynamicDataSource 的定義看出,他返回的是DynamicDataSourceHolder.getDataSouce()值,咱們須要在程序運行時調用DynamicDataSourceHolder.putDataSource()方法,對其賦值。下面是咱們實現的核心部分,也就是AOP部分,DataSourceAspect定義以下:

Java代碼 

 收藏代碼

  1. public class DataSourceAspect {  
  2.   
  3.     public void before(JoinPoint point)  
  4.     {  
  5.         Object target = point.getTarget();  
  6.         String method = point.getSignature().getName();  
  7.   
  8.         Class<?>[] classz = target.getClass().getInterfaces();  
  9.   
  10.         Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())  
  11.                 .getMethod().getParameterTypes();  
  12.         try {  
  13.             Method m = classz[0].getMethod(method, parameterTypes);  
  14.             if (m != null && m.isAnnotationPresent(DataSource.class)) {  
  15.                 DataSource data = m  
  16.                         .getAnnotation(DataSource.class);  
  17.                 DynamicDataSourceHolder.putDataSource(data.value());  
  18.                 System.out.println(data.value());  
  19.             }  
  20.               
  21.         } catch (Exception e) {  
  22.             // TODO: handle exception  
  23.         }  
  24.     }  
  25. }  

 

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

Xml代碼 

 收藏代碼

  1. <bean id="masterdataSource"  
  2.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  3.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  4.         <property name="url" value="jdbc:mysql://127.0.0.1:3306/shop" />  
  5.         <property name="username" value="root" />  
  6.         <property name="password" value="yangyanping0615" />  
  7.     </bean>  
  8.   
  9.     <bean id="slavedataSource"  
  10.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  11.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  12.         <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />  
  13.         <property name="username" value="root" />  
  14.         <property name="password" value="yangyanping0615" />  
  15.     </bean>  
  16.       
  17.         <beans:bean id="dataSource" class="com.air.shop.common.db.DynamicDataSource">  
  18.         <property name="targetDataSources">    
  19.               <map key-type="java.lang.String">    
  20.                   <!-- write -->  
  21.                  <entry key="master" value-ref="masterdataSource"/>    
  22.                  <!-- read -->  
  23.                  <entry key="slave" value-ref="slavedataSource"/>    
  24.               </map>    
  25.                 
  26.         </property>    
  27.         <property name="defaultTargetDataSource" ref="masterdataSource"/>    
  28.     </beans:bean>  
  29.   
  30.     <bean id="transactionManager"  
  31.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  32.         <property name="dataSource" ref="dataSource" />  
  33.     </bean>  
  34.   
  35.   
  36.     <!-- 配置SqlSessionFactoryBean -->  
  37.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  38.         <property name="dataSource" ref="dataSource" />  
  39.         <property name="configLocation" value="classpath:config/mybatis-config.xml" />  
  40.     </bean>  

 

  在spring的配置中增長aop配置

Xml代碼 

 收藏代碼

  1. <!-- 配置數據庫註解aop -->  
  2.     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>  
  3.     <beans:bean id="manyDataSourceAspect" class="com.air.shop.proxy.DataSourceAspect" />  
  4.     <aop:config>  
  5.         <aop:aspect id="c" ref="manyDataSourceAspect">  
  6.             <aop:pointcut id="tx" expression="execution(* com.air.shop.mapper.*.*(..))"/>  
  7.             <aop:before pointcut-ref="tx" method="before"/>  
  8.         </aop:aspect>  
  9.     </aop:config>  
  10.     <!-- 配置數據庫註解aop -->  

 

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

Java代碼 

 收藏代碼

  1. public interface UserMapper {  
  2.     @DataSource("master")  
  3.     public void add(User user);  
  4.   
  5.     @DataSource("master")  
  6.     public void update(User user);  
  7.   
  8.     @DataSource("master")  
  9.     public void delete(int id);  
  10.   
  11.     @DataSource("slave")  
  12.     public User loadbyid(int id);  
  13.   
  14.     @DataSource("master")  
  15.     public User loadbyname(String name);  
  16.       
  17.     @DataSource("slave")  
  18.     public List<User> list();  
  19. }  

 

 

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



 

 

從圖中能夠看出,登陸的用戶和用戶列表的數據是不一樣的,也驗證了咱們的實現,登陸讀取Master庫,用戶列表讀取Slave庫。

例子來源:

http://www.cnblogs.com/surge/p/3582248.html

 

 

 2、配置動態數據源

Xml代碼 

 收藏代碼

  1.   <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">  
  2.     <property name="jndiName">  
  3.         <value>java:/datasources/visesbdb</value>  
  4.     </property>  
  5.   </bean>  
  6.     
  7.   <!-- config dynamicDataSource -->  
  8.   <bean id="dynamicDataSource" class="com.vispractice.soa.lightesb.common.datasource.MutiDataSourceBean">  
  9. <property name="targetDataSources">  
  10.     <map key-type="java.lang.String">  
  11.         <entry value-ref="dataSource" key="dataSource"></entry>  
  12.     </map>  
  13. </property>  
  14.     <property name="defaultTargetDataSource" ref="dataSource"></property>  
  15.   </bean>  
  16.     
  17.   <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>  
  18.   
  19.   <!-- Hibernate SessionFactory -->  
  20.   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  21.       <property name="dataSource" ref="dynamicDataSource"/>  
  22.       <property name="packagesToScan">  
  23.         <list>  
  24.             <value>com.vispractice.soa.lightesb.bean</value>  
  25.         </list>  
  26.       </property>  
  27.       <property name="hibernateProperties">  
  28.           <props>  
  29. <prop key="connection.useUnicode">true</prop>  
  30. <prop key="connection.characterEncoding">UTF-8</prop>  
  31. <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  32. <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
  33. <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  34. <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>  
  35. <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>  
  36. <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>  
  37.    </props>              
  38.       </property>  
  39.   </bean>  
  40.   
  41.   <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->  
  42.   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  43.       <property name="sessionFactory" ref="sessionFactory"/>  
  44.   </bean>  

 

Java代碼 

 收藏代碼

  1. /** 
  2.  * 在applicationContext中配置本地數據源做爲默認數據源 
  3.  * 讀取project-datasource-jndi.properties中的jndi名稱獲取其餘節點的數據源 
  4.  * 該文件放在D:\jboss-5.1.0.GA\server\default\conf\props 目錄下 
  5.  * 
  6.  */  
  7. public class MutiDataSourceBean extends AbstractRoutingDataSource implements ApplicationContextAware {  
  8.   
  9.     private static final Logger logger = LoggerFactory.getLogger(MutiDataSourceBean.class);  
  10.   
  11.     private static ApplicationContext ctx;  
  12.       
  13.     private Map<Object,Object> tds = new HashMap<Object,Object>();  
  14.   
  15.     @Override  
  16.     public void setApplicationContext(ApplicationContext applicationContext)  
  17.             throws BeansException {  
  18.         ctx = applicationContext;  
  19.     }  
  20.   
  21.     @Override  
  22.     protected Object determineCurrentLookupKey() {  
  23.         return DataSourceContextHolder.getDataSourceType();  
  24.     }  
  25.   
  26.     //重寫InitializingBean類中方法  
  27.     @Override  
  28.     public void afterPropertiesSet() {  
  29.         logger.info("Init MutiDataSource start...");  
  30.         try {  
  31.             initailizeMutiDataSource();  
  32.         } catch (Exception e) {  
  33.             logger.error("Init MutiDataSource error...", e);  
  34.         }  
  35.         logger.info("Init MutiDataSource end...");  
  36.         super.afterPropertiesSet();  
  37.     }  
  38.   
  39.     /** 
  40.      * 讀取配置文件中的jndi名稱,獲取數據源 
  41.      * @throws Exception 
  42.      */  
  43.     private void initailizeMutiDataSource() throws Exception {  
  44.         // 讀取數據源配置文件  
  45.         ResourceBundle lw = ResourceBundle.getBundle("props.project-datasource-jndi");  
  46.           
  47.         // 初始化jndi context  
  48.         Context jndiCtx = new InitialContext();  
  49.           
  50.         DefaultListableBeanFactory dlbf  = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();  
  51.           
  52.         // 獲取配置的數據源  
  53.         for(String key : lw.keySet()){  
  54.             Object ds = jndiCtx.lookup(lw.getString(key));  
  55.             // 將數據源交給spring管理  
  56.             dlbf.registerSingleton(key, ds);  
  57.               
  58.             tds.put(key, ds);  
  59.         }  
  60.         super.setTargetDataSources(tds);  
  61.     }  
  62.   
  63.     @Override  
  64.     public void setTargetDataSources(Map<Object, Object> targetDataSources) {  
  65.         tds = targetDataSources;  
  66.         super.setTargetDataSources(targetDataSources);  
  67.     }  
  68.   
  69. }  

 

Java代碼 

 收藏代碼

  1. /** 
  2.  * 經過ThreadLocal來存儲當前所使用數據源對應的key 
  3.  *  
  4.  */  
  5. public class DataSourceContextHolder {  
  6.   
  7.     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
  8.   
  9.     public static void setDataSourceType(String dataSourceType) {  
  10.         contextHolder.set(dataSourceType);  
  11.     }  
  12.   
  13.     public static String getDataSourceType() {  
  14.         return contextHolder.get();  
  15.     }  
  16.   
  17.     public static void clearDataSourceType() {  
  18.         contextHolder.remove();  
  19.     }  
  20. }  

 

查詢前設置值:

Java代碼 

 收藏代碼

  1. MutiDataSourceUtil.determineTargetDataSourceByInstanceUUID(EsbServiceInstanceV.getInstanceUUID());  
  2.         Map<String,Object> result = esbServiceMonitorDao.findEsbServiceInstanceVPagedList(pageQueryParameter, EsbServiceInstanceV);  
  3.         // reset datasource  
  4.         DataSourceContextHolder.clearDataSourceType();  

 

Java代碼 

 收藏代碼

  1. public class MutiDataSourceUtil {  
  2.       
  3.     /** 
  4.      * 經過實例UUID切換到對應的數據源 
  5.      *  
  6.      * @param instanceUUID 
  7.      */  
  8.     public static void determineTargetDataSourceByInstanceUUID(String instanceUUID) {  
  9.         if(StringUtils.isNotBlank(instanceUUID) && StringUtils.contains(instanceUUID, '-')){  
  10.             DataSourceContextHolder.setDataSourceType(StringUtils.substringBefore(instanceUUID, "-"));  
  11.         }  
  12.     }  
  13.   
  14. }  

 

lightesb-datasource-jndi.properties:

Xml代碼 

 收藏代碼

  1. N1=java:/datasources/visesbdb  
  2. N2=java:/datasources/n2visesbdb  

 

實例號如:

N1-AB2DFE3C48BA43D699529868B20152CC

相關文章
相關標籤/搜索