Dynamic switching database based on Abstractroutingdatasource

Source: Internet
Author: User

When the project develops to a certain stage, the database must be optimized. The database is generally horizontally and vertically çeku, but the problem is that when we operate the database, we need to get a connection to the database we need in advance based on the segmentation rules, which can significantly increase the burden on the programmer.
For example, we will "user information database" in accordance with the user registration of the year and the library, in the user registration, the user is assigned a YYYYMM beginning with a unique indicator, so that we can quickly locate the sub-database after segmentation. So the question is, how do we get the data source we need dynamically and conveniently in the project? Spring provides a solution for dynamic Data source switching based on Abstractroutingdatasource.
Abstractroutingdatasource's class structure:

To use it, just rewrite the Determinecurrentlookupkey method, and before explaining his role, look at the downgrade with his position:

Private Map

    protectedDataSourceDeterminetargetdatasource() {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 NewIllegalStateException ("cannot determine target DataSource for lookup key ["+ LookupKey +"]"); }returnDataSource; }

As you can see, the return value of Determinecurrentlookupkey is used as the map key to find the database connection. The Determinetargetdatasource method is usually used to return to the caller datasource, so we can implement the dynamic switching of the database by overriding the two methods.

First, define a bean to hold the database information, as well as the map key, the database connection as value.

publicclass DatabaseDefineBean {    private String userName;    private String passWord;    private String url;    ...getter/setter}

Write our own data source

 Public  class mydatasource extends abstractroutingdatasource {    PrivateString Driverclassname;StaticThreadlocal<databasedefinebean> Definebeans =NewThreadlocal<databasedefinebean> ();@Override    protectedObjectDeterminecurrentlookupkey() {returnDefinebeans.get (); }@Override    protectedDataSourceDeterminetargetdatasource() {Drivermanagerdatasource DataSource = Getdatasource ((databasedefinebean) Determinecurrentlookupkey ());returnDataSource; }PrivateDrivermanagerdatasourceGetdatasource(Databasedefinebean databse) {Drivermanagerdatasource DataSource =NewDrivermanagerdatasource (Databse.geturl (), Databse.getusername (), Databse.getpassword ());returnDataSource; }}

Here use Spring+mybatis Test (source code and database file download):

String UserName ="Writeuser";String PassWord ="Writeuser";String URL ="Jdbc:mysql://192.168.1.61:3306/databaseroute";@Test public void Test () {ApplicationContext context = new Classpathxmlapplicationcontext (New string[]{"/com/smart/config/spring-jdbc.xml"});myDataSource. Setdefinebeans(New Databasedefinebean (UserName, PassWord, URL));DataSource DataSource = Context. Getbean(DataSource. Class);System. out. println(DataSource);Sqlsessiontemplate sessiontemplate = Context. Getbean(sqlsessiontemplate. Class); Databaseinfomapper mapper = Sessiontemplate. Getsqlsessionfactory(). Opensession(). Getmapper(Databaseinfomapper. Class);list<?> list = Mapper. SelectAll();System. out. println(list);}

So how to switch dynamically? Here we use the threadlocal to save a copy for each thread, so we can easily get the data source we need by setting up database basic information before we manipulate it.

MyDataSource.setDefineBeans(new DatabaseDefineBean(userName, passWord, url));

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dynamic switching database based on Abstractroutingdatasource

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.