`
小天蝎
  • 浏览: 143604 次
  • 性别: Icon_minigender_1
  • 来自: 南宁
社区版块
存档分类
最新评论

Dynamic DataSource Routing

阅读更多
<!---->Mark Fisher

Spring 2.0.1 introduced an AbstractRoutingDataSource. I believe that it deserves attention, since (based on frequent questions from clients) I have a hunch that there are quite a few 'home-grown' solutions to this problem floating around. That combined with the fact that it is trivial to implement yet easy to overlook, and now I have several reasons to dust off my corner of the Interface21 team blog.

The general idea is that a routing DataSource acts as an intermediary - while the 'real' DataSource can be determined dynamically at runtime based upon a lookup key. One potential use-case is for ensuring transaction-specific isolation levels which are not supported by standard JTA. For that, Spring provides an implementation: IsolationLevelDataSourceRouter. Consult its JavaDoc for a detailed description including configuration examples. Another interesting use-case is determination of the DataSource based on some attribute of the current user's context. What follows is a rather contrived example to demonstrate this idea.

First, I created a Catalog that extends Spring 2.0's SimpleJdbcDaoSupport. That base class only requires an instance of any implementation of javax.sql.DataSource, and then it creates a SimpleJdbcTemplate for you. Since it extends JdbcDaoSupport, the JdbcTemplate is also available. However, the "simple" version provides many nice Java 5 conveniences. You can read more detail about that in this blog by Ben Hale.

Anyways, here's the code for my Catalog:

java 代码
 
  1. package blog.datasource;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5. import java.util.List;  
  6.   
  7. import org.springframework.jdbc.core.simple.ParameterizedRowMapper;  
  8. import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;  
  9.   
  10. public class Catalog extends SimpleJdbcDaoSupport {  
  11.          
  12.    public List<Item> getItems() {  
  13.       String query = "select name, price from item";  
  14.       return getSimpleJdbcTemplate().query(query, new ParameterizedRowMapper<Item>() {  
  15.             public Item mapRow(ResultSet rs, int row) throws SQLException {  
  16.                String name = rs.getString(1);  
  17.                double price = rs.getDouble(2);  
  18.                return new Item(name, price);  
  19.             }  
  20.       });  
  21.    }  
  22. }  

As you can see, the Catalog simply returns a list of Item objects. The Item just contains name and price properties:

java 代码
 
  1. package blog.datasource;  
  2.   
  3. public class Item {  
  4.   
  5.    private String name;  
  6.    private double price;  
  7.          
  8.    public Item(String name, double price) {  
  9.       this.name = name;  
  10.       this.price = price;  
  11.    }  
  12.   
  13.    public String getName() {  
  14.       return name;  
  15.    }  
  16.   
  17.    public double getPrice() {  
  18.       return price;  
  19.    }  
  20.   
  21.    public String toString() {  
  22.       return name + " (" + price + ")";  
  23.    }  
  24.   
  25. }  

Now, in order to demonstrate multiple DataSources, I created an enum for different Customer types (representing "levels" of membership I guess), and I created three different databases - so that each type of customer would get a distinct item list (I did mention that this would be a contrived example didn't I?). The important thing is that each of the databases are equivalent in terms of the schema. That way the Catalog's query will work against any of them - just returning different results. In this case, it's just the "item" table with 2 columns: name and price. And… here is the enum:

java 代码
 
  1. public enum CustomerType {  
  2.    BRONZE,  
  3.    SILVER,  
  4.    GOLD  
  5. }  

It's time to create some bean definitions. Since I have 3 datasources where everything is the same except for the port number, I created a parent bean so that the shared properties can be inherited. Then, I added the 3 bean definitions to represent the per-CustomerType DataSources:

<bean></bean> 
xml 代码
 
  1. <bean id="parentDataSource"  
  2.          class="org.springframework.jdbc.datasource.DriverManagerDataSource"  
  3.          abstract="true">  
  4.    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>  
  5.    <property name="username" value="sa"/>  
  6. </bean>  
  7.                  
  8. <bean id="goldDataSource" parent="parentDataSource">  
  9.    <property name="url" value="jdbc:hsqldb:hsql://localhost:${db.port.gold}/blog"/>  
  10. </bean>  
  11.   
  12. <bean id="silverDataSource" parent="parentDataSource">  
  13.    <property name="url" value="jdbc:hsqldb:hsql://localhost:${db.port.silver}/blog"/>  
  14. </bean>  
  15.   
  16. <bean id="bronzeDataSource" parent="parentDataSource">  
  17.    <property name="url" value="jdbc:hsqldb:hsql://localhost:${db.port.bronze}/blog"/>  
  18. </bean>  
  19.   
  20. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  21.    <property name="location" value="classpath:/blog/datasource/db.properties"/>  
  22. </bean>  

Notice that I added a PropertyPlaceholderConfigurer so that I could externalize the port numbers in a "db.properties" file, like so:

java 代码
 
  1. db.port.gold=9001  
  2. db.port.silver=9002  
  3. db.port.bronze=9003  

Now things start to get interesting. I need to supply the "routing" DataSource to my Catalog so that it can dynamically get connections from the 3 different databases at runtime based on the current customer's type. As I mentioned, the AbstractRoutingDataSource can be rather simple to implement. Here is my implementation:

java 代码
 
  1. package blog.datasource;  
  2.   
  3. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  4.   
  5. public class CustomerRoutingDataSource extends AbstractRoutingDataSource {  
  6.   
  7.    @Override  
  8.    protected Object determineCurrentLookupKey() {  
  9.       return CustomerContextHolder.getCustomerType();  
  10.    }  
  11. }  

…and the CustomerContextHolder simply provides access to a thread-bound CustomerType. In reality, the 'context' would likely hold more information about the customer. Also note that if you are using Acegi, then you could retrieve some information from the userDetails. For this example, it's just the customer "type":

java 代码
 
  1. public class CustomerContextHolder {  
  2.   
  3.    private static final ThreadLocal<CustomerType> contextHolder =  
  4.             new ThreadLocal<CustomerType>();  
  5.          
  6.    public static void setCustomerType(CustomerType customerType) {  
  7.       Assert.notNull(customerType, "customerType cannot be null");  
  8.       contextHolder.set(customerType);  
  9.    }  
  10.   
  11.    public static CustomerType getCustomerType() {  
  12.       return (CustomerType) contextHolder.get();  
  13.    }  
  14.   
  15.    public static void clearCustomerType() {  
  16.       contextHolder.remove();  
  17.    }  
  18. }  

Finally, I just need to configure the catalog and routing DataSource beans. As you can see, the "real" DataSource references are provided in a Map. If you provide Strings, they can be resolved as JNDI names (or any custom resolution strategy can be provided - see the JavaDoc). Also, I've simply set the 'bronzeDataSource' as the default:

<bean></bean> 
xml 代码
 
  1. <bean id="catalog" class="blog.datasource.Catalog">  
  2.    <property name="dataSource" ref="dataSource"/>  
  3. </bean>  
  4.   
  5. <bean id="dataSource" class="blog.datasource.CustomerRoutingDataSource">  
  6.    <property name="targetDataSources">  
  7.       <map key-type="blog.datasource.CustomerType">  
  8.          <entry key="GOLD" value-ref="goldDataSource"/>  
  9.          <entry key="SILVER" value-ref="silverDataSource"/>  
  10.       </map>  
  11.    </property>  
  12.    <property name="defaultTargetDataSource" ref="bronzeDataSource"/>  
  13. </bean>  

Of course I'd like to see this working, so I've created a simple test (extending one of Spring's integration test support classes). I added 3 items to the "gold" database, 2 items to the "silver" database, and only 1 item to the "bronze" database. This is the test:

java 代码
 
  1. public class CatalogTests extends AbstractDependencyInjectionSpringContextTests {  
  2.   
  3.    private Catalog catalog;  
  4.   
  5.    public void setCatalog(Catalog catalog) {  
  6.       this.catalog = catalog;  
  7.    }  
  8.   
  9.    public void testDataSourceRouting() {  
  10.       CustomerContextHolder.setCustomerType(CustomerType.GOLD);  
  11.       List<Item> goldItems = catalog.getItems();  
  12.       assertEquals(3, goldItems.size());  
  13.       System.out.println("gold items: " + goldItems);  
  14.   
  15.       CustomerContextHolder.setCustomerType(CustomerType.SILVER);  
  16.       List<Item> silverItems = catalog.getItems();  
  17.       assertEquals(2, silverItems.size());  
  18.       System.out.println("silver items: " + silverItems);  
  19.          
  20.       CustomerContextHolder.clearCustomerType();  
  21.       List<Item> bronzeItems = catalog.getItems();  
  22.       assertEquals(1, bronzeItems.size());  
  23.       System.out.println("bronze items: " + bronzeItems);                
  24.    }  
  25.   
  26.    protected String[] getConfigLocations() {  
  27.       return new String[] {"/blog/datasource/beans.xml"};  
  28.    }     
  29. }  

…and rather than simply taking a screenshot of the green bar, you'll notice I've provided some console output - the results!:

java 代码
 
  1. gold items: [gold item #1 (250.0), gold item #2 (325.45), gold item #3 (55.6)]  
  2. silver items: [silver item #1 (25.0), silver item #2 (15.3)]  
  3. bronze items: [bronze item #1 (23.75)]  

As you can see, the configuration is simple. Better still, the data-access code is not concerned with looking up different DataSources. For more information, consult the JavaDoc for AbstractRoutingDataSource.

分享到:
评论

相关推荐

    基于Oracle数据库的读写分离电子商务系统的设计与实现.docx

    通过采用Oracle DataGuard技术和Spring Dynamic DataSource Routing等技术手段,系统能够有效地提升数据处理能力,确保在大量用户访问的情况下仍能保持良好的性能。此外,通过细致地规划用户中心和商品中心的功能及...

    spring1.2 操作多个数据源

    2. 动态数据源路由(Dynamic DataSource Routing): Spring提供了一个名为`AbstractRoutingDataSource`的抽象类,它可以动态决定使用哪个数据源。你需要创建一个继承自`AbstractRoutingDataSource`的类,并重写`...

    Ssh多数据源.doc

    首先,多数据源解决方案的核心在于Spring 3的动态数据源路由(Dynamic DataSource Routing)。这个功能允许系统在运行时动态地选择要使用的数据源,而不需要重启服务。通过配置一个主数据源,并在需要时切换到其他...

    druid-master

    Druid是阿里巴巴开源的一个高性能、强大的数据库连接池组件,它的全称是Dynamic Routing Data Source,即动态数据源。在Java开发中,特别是在Spring Boot项目中,Druid被广泛用于管理数据库连接,提供高效的连接池...

    配置Druid连接池需要的jar包-druid-1.0.15.jar

    Druid是阿里巴巴开源的一个高效、强大的数据库连接池组件,它的全称是Dynamic Routing Data Source,即动态路由数据源。Druid连接池在Java Web开发中被广泛使用,它提供了监控、扩展性、性能优化等特性,使得数据库...

    druid-1.0.9.7z

    阿里Druid是一个高效、强大的Java数据库连接池组件,它的全称是Dynamic Routing Data Source,由阿里巴巴开源并维护。Druid的主要目标是提供监控、扩展性和性能优化,它在JDBC数据库连接池领域有着广泛的应用。在...

    druid-1.1.21.zip

    阿里Druid,全称为Dynamic Routing Data Source,是一款高效、强大的数据库连接池组件。在2019年11月,Druid发布了最新的版本1.1.21,该版本经过大规模项目的实际检验,稳定性和性能得到了广泛认可。作为一款广泛...

    最新版druid 数据库连接池 druid-1.1.21.jar

    Druid是阿里巴巴开源的一个高效、强大的数据库连接池组件,它的全称是Dynamic Routing Data Source,即动态路由数据源。在Java Web开发中,数据库连接池扮演着至关重要的角色,它负责管理数据库连接,提高数据库操作...

    druid-1.0.9.rar

    Druid是阿里巴巴开源的一个高效、强大的数据库连接池组件,它的全称是Dynamic Routing Data Source,动态数据源。在Java开发中,数据库连接池是系统性能优化的重要环节,它负责管理数据库连接,提供连接的复用,避免...

    furnace-2.2.0.Final.zip

    Druid,全称Dynamic Routing Database,是一个高性能、开源的Java数据库连接池。它不仅提供了数据库连接池功能,还包含了SQL解析、监控、拦截器等丰富的特性,能够帮助开发者更好地管理和优化数据库连接。Druid ...

    druid-1.2.8.rar

    Druid,全名Dynamic Routing Data Source,是由阿里巴巴开源的一款高效、强大的数据库连接池组件。它不仅是一个优秀的JDBC连接池,还包含了监控统计、SQL解析、日志、拦截器等功能,是现代Java企业级应用中的常见...

Global site tag (gtag.js) - Google Analytics