Spring is configured as follows
<!--main data source-<bean id= "Masterdatasource" class= " Org.springframework.jdbc.datasource.DriverManagerDataSource "> <property name=" driverclassname "value=" COM.M Ysql.jdbc.Driver "/><property name=" url "value=" jdbc:mysql://127.0.0.1/test1?useunicode=true& Characterencoding=utf8 "/><property name=" username "value=" root "/><property name=" password "value=" 123456 "/> </bean> <!--from data source-<bean id=" Slavedatasource "class=" Org.springframewo Rk.jdbc.datasource.DriverManagerDataSource "> <property name=" driverclassname "value=" Com.mysql.jdbc.Driver " /><property name= "url" value= "Jdbc:mysql://127.0.0.1/test2?useunicode=true&characterencoding=utf8"/ ><property name= "username" value= "root"/><property name= "password" value= "123456"/> </bean> &l T;bean id= "DataSource" class= "C.p.aop.dynamicdatasource" > <property name= "targetdatasources" ><map key-type= "java.lang.String" > <entry key= "Slave" value-ref= "Slavedatasource"/> <entry key= "Master" value-ref= "Masterdatasource"/> </map> </property> <property name= "Defaulttargetdatasource" ref= "Masterdatasource"/> </bean> <!--configuration JdbcTemplate, can be Direct operation of database via JdbcTemplate--><bean id= "JdbcTemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" >< Property Name= "DataSource" ref= "DataSource"/></bean><!--Configure public class objects--><bean id= "Basedao" class= " Cq.base.dao.impl.SSH2BaseDaoImpl "><property name=" sessionfactory "ref=" Sessionfactory "/></bean> <!--configuring public class Objects <bean id= "Pagedao" class= "Cq.base.dao.impl.PageDaoImpl" ><property name= "sessionfactory" ref = "Sessionfactory"/></bean>--><!--configuration sessionfactory, annotation mode configuration--><bean id= "Sessionfactory" class = "Org.springframework.orm.hibernate3.annotation.AnnotationSessionFacTorybean "><property name=" DataSource "ref=" DataSource "/><property name=" Packagestoscan "value=" C.p.entity "/><property name=" annotatedclasses "><list><value>cq.base.entity.logbean</ Value></list></property><property name= "hibernateproperties" ><props><!--<prop key= "Hibernate.dialect" >org.hibernate.dialect.Oracle10gDialect</prop>--><!--<prop key= " Hibernate.dialect ">org.hibernate.dialect.sqlserverdialect</prop>--><prop key=" Hibernate.dialect " >org.hibernate.dialect.mysqldialect</prop><prop key= "Hibernate.hbm2ddl.auto" >update</prop> <prop key= "Hibernate.show_sql" >true</prop><prop key= "Hibernate.cache.use_second_level_cache" > True</prop><prop key= "Hibernate.cache.provider_class" >org.hibernate.cache.ehcacheprovider</prop ><prop key= "Hibernate.cache.use_query_cache" >true</prop></props></property></bean > <!--Toggle Data Source--<bean id= "Datasourceadvice" class= "C.p.aop.datasourceadvice" ></bean> <aop:con fig> <aop:pointcut id= "businessservice" expression= "Execution (* *). *service.* (..)) " /> <aop:advisor pointcut-ref= "businessservice" advice-ref= "Datasourceadvice"/> </aop:config>
Three class mates are required here
Dynamicdatasource <pre name= "code" class= "HTML" >datasourceadvice
C.p.aop.dynamicdatasource.java as follows:
Public class Dynamicdatasource extends Abstractroutingdatasource { @Override protected Object Determinecurrentlookupkey () { return Datasourceswitcher.getdatasource (); } Public Logger Getparentlogger () {//TODO auto-generated method Stubreturn null;} Public <T> T Unwrap (class<t> iface,string m) throws SQLException {//TODO auto-generated method Stubreturn nul l;} public boolean iswrapperfor (class<?> iface,string m) throws SQLException {//TODO auto-generated method Stubreturn F alse;} }
C.p.aop.datasourceadvice.java, configure the following public class Datasourceadvice implements Methodbeforeadvice, Afterreturningadvice , Throwsadvice { //service method is called before execution public void before (method, Object[] args, Object target) throws Throwable { System.out.println (" Entry point: "+ Target.getclass ()." GetName () + "class" + method.getname () + "method"); if (Method.getname (). StartsWith ("add") | | Method.getname (). StartsWith ("add") | | Method.getname (). StartsWith ("Update") | | Method.getname (). StartsWith ("delete")) { SYSTEM.OUT.PRINTLN ("Switch to: Master"); Datasourceswitcher.setmaster (); } else { System.out.println ("Switch to: Slave"); Datasourceswitcher.setslave (); } } // Called after the service method is executed public void afterreturning (object arg0, method, object[] args, Object t Arget) throws Throwable { } //Throw exception after being called & nbsp; public void Afterthrowing (method, object[] args, Object target, Exception ex) throws Throwable { Datasourceswitcher.Setslave (); System.out.println ("Abnormal, switch to: Slave"); } }<pre name= "code" class= "HTML" >datasourceswitcher.java code is as follows public class Datasourceswitcher { @SuppressWarnings ("Rawtypes") private static Final ThreadLocal Contextholder = new ThreadLocal (); @SuppressWarnings ("unchecked") public static void Setdatasource (String dataSource) { assert.notnull (DataSource, " DataSource cannot be null "); Contextholder.set (DataSource); } public static void Setmaster () { Cleardatasource (); } public static void Setslave () { Setdatasource ("slave"); } public static String Getdatasource () { return (String) contextholder.get (); } public static void Cleardatasource () { Contextholder.remove (); } }
The configuration of these can be read and write separation, but one problem is that when inserting data, the program will insert data into the main database, when the database does not have this inserted data, so that the data is not synchronized, MySQL has a way to synchronize the master database from the database method.
We can follow these steps to achieve
1. Configure the my.ini file for the primary database, and add it on the last side
#---------------------------------------------
server-id=242
Log-bin=mysql-bin
Relay-log=relay-bin
Relay-log-index=relay-bin-index
Replicate-do-db= the database to synchronize
#---------------------------------------------
Restart the MySQL service.
2. Also configure the corresponding my.ini file from the database
#---------------------------------------------
server-id=243
Log-bin=mysql-bin
Relay-log=relay-bin
Relay-log-index=relay-bin-index
Replicate-do-db= the database to synchronize
#---------------------------------------------
Restart the MySQL service.
3. Configure synchronization from the database
Beat the following command from the database
Service 242 use the MySQL command line tool to execute the following statement:
mysql> stop Slave;
mysql> Change Master to master_host= ' primary database IP', master_user= ' root ', master_password= ' ABCD ';
mysql> start slave;
Mysql> show Slave status\g;
This allows for synchronization to happen.
Spring Hibernate configuration Toggle Data source for read-write separation