Mybatis Multi-Data 소스 구성 (읽기 쓰기 분리)
우선,이 기사에서 구성을 사용하는 가장 직접적인 방법은 실제로 사용하기에 매우 귀찮을 수 있습니다.
실제 애플리케이션에는 여러 조합이있을 수 있습니다. 이 기사의 의미를 이해하고 엄격하게 사용하지 않을 수 있습니다.
여러 데이터 소스가있는 상황
1. 마스터와 노예
일반적으로 MySQL에 마스터와 여러 노예가있는 경우입니다. 이 기사의 예는 마스터와 노예가있는 경우이지만 두 개의 데이터 소스 만 있으므로 직접 구성을 사용하기에는 너무 번거 롭지는 않지만 후속 확장에는 도움이되지 않습니다. 주로 설명하기위한 예로 사용됩니다. 실제 작업에서 신중하게 고려하십시오.
2. 도서관을 나누기
비즈니스 독립성이 강하고 데이터 볼륨이 크면 동시성을 개선하기 위해 테이블이 나눌 수 있습니다. 데이터베이스를 분할 한 후 각 데이터베이스는 데이터 소스를 구성해야합니다.
이 경우이 기사를 참조 할 수 있지만 각 데이터베이스에 해당하는 맵퍼는 다른 패키지에서 편리하게 구별되고 구성되어야합니다.
또한 데이터베이스 파티션이 있으면 마스터 슬레이브 케이스가 있습니다. 데이터베이스 슬레이브 라이브러리가 너무 많으면 위에 제공된 방법을 참조하거나 문제를 해결하는 다른 방법을 찾으십시오.
맵퍼 하청 계약
분할의 경우, 다른 데이터베이스의 맵퍼는 다른 패키지 아래에 배치해야합니다.
마스터와 노예의 경우, 동일한 매퍼를 동시에 읽고 쓰여질 것입니다. 두 개를 만드는 것은 적절하지 않으며 같은 것을 사용하십시오. 그러나이 경우 스프링은 매퍼의 이름을 자동으로 생성하고 유형이 동일하므로 맵퍼 인터페이스에 직접 주입 할 수는 없습니다. sqlsession을 통해 해결해야합니다.
스프링 기본 구성
ApplicationContext.xml
<beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns : context = "http://wwww.spramframett" xmlns : aop = "http://www.springframework.org/schema/aop"xsi : schemalocation = "http://www.springframework.org/schema/beans http://ww.springframework.org/schema/spride-bean.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.spramework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <context : component-scan base-package ="com.isea533.service "/> <context : property-placeholder 위치 ="classpath : config.properties "/> <aopj-autj-autj-autj-autropxy Resource = "Spring-datasource-master.xml"/> <import resource = "Spring-datasource-slave.xml"/>
이 파일은 주로 Spring-datasource-master.xml 및 Spring-datasource-slave.xml을 소개합니다.
Spring-datasource-master.xml
<beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns : tx = "http://wwww.spramfram.org. xmlns : aop = "http://www.springframework.org/schema/aop"xsi : schemalocation = "http://www.springframework.org/schema/beans http://ww.springframework.org/schema/spride-bean.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://wwwww.spramframframegramegramerwork.org http://www.springframework.org/schema/aop/spring-aop.xsd "> <bean id ="dataSourcemaster "init-method ="init "닫기"> <property name = "driverclassName"value = "$ {mas value = "$ {mas value = "1"/> <속성 이름 = "maxwait"value = "60000"/> <property name = "minidle"value = "1"/> <속성 이름 = "timebetweenvictionRunsmillis"value = "60000"/> <속성 이름 = "minevictableDletimEmillis"value = "300000"valy vancious ""validation " 이름 = "testwhileIdle"value = "true"/> <property name = "testonborring"value = "false"/> <property name = "testonreturn"value = "false"/> </bean> <bean id = "sqlsessionfactory1"> <property name = "dataSource"ref = "dataSourcemaster"/> <property name = "mapperlocations"> <value> classpath : mapper/*. xml </value> </array> </are> </bean> <ean> <bean> <property name = "basepackage"value = "com.isea533.mybatis.mapper"/> <property name = "sqlsessionactorybeanname"value = "sqlsessionficatory1"/> </bean> </bean> < "sqlsessionfactory1". 스코프 = "프로토 타입"> <생성자-arg index = "0"ref = "sqlsessionfactory1"/> </bean> <aop : config> <aop : pointcut id = "appservice"expression = "execution (*com.isea533.mybatis.service ..*service*.*(..))") ")"). PointCut-Ref = "AppService"/> </aop : config> <tx : tx : 조언 id = "txadvice1"transaction-manager = "transactionmanager1 : attributes> <tx : method name ="select*"read-only ="true "/> <tx :"method "="read name = "true": <tx : method ": method": method ":"true ": read-donly = "true"/> <tx : 메소드 이름 = "get*"read-foly = "true"/> <tx : method name = "*"/> </tx : attributes> </tx : joad> <bean id = "transactionManager1"> <property name = "dataSource"ref = "dataSourcemaster"/> </beans>Spring-datasource-slave.xml
IT와 마스터 사이에는 거의 차이가 없습니다. 주로 ID 이름과 데이터 소스 구성 사이에 차이가 있기 때문입니다.
<beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns : tx = "http://wwww.spramfram.org. xmlns : aop = "http://www.springframework.org/schema/aop"xsi : schemalocation = "http://www.springframework.org/schema/beans http://ww.springframework.org/schema/spride-bean.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://wwwww.spramframframegramegramerwork.org http://www.springframework.org/schema/aop/spring-aop.xsd "> <bean id ="dataSourcesLave "init-method ="init "닫기"> <property name = "driverClassName"value = "$ {slave.jdbc.driverclass}"/> value = "$ {slave.jdbc.url}"/> <속성 이름 = "username"value = "$ {slave.jdbc.user}"/> <property name = "password"value = "$ {slave.jdbc.password}"/> <property name = "value ="stat "/>"value "="maxactive ""maxactive ". value = "1"/> <속성 이름 = "maxwait"value = "60000"/> <property name = "minidle"value = "1"/> <속성 이름 = "timebetweenvictionRunsmillis"value = "60000"/> <속성 이름 = "minevictableDletimEmillis"value = "300000"valy vancious ""validation " 이름 = "testwhileIdle"value = "true"/> <property name = "testonborring"value = "false"/> <property name = "testonreturn"value = "false"/> </bean> <bean id = "sqlsessionfactory2"> <property name = "dataSource"ref = "dataSourslave"/>> <propertlocations ""mapperlocations ""mapperlocations ". <value> classPath : Mapper/*. xml </value> </array> </are> </bean> <ean> <bean> <property name = "basepackage"value = "com.isea533.mybatis.mapper"/> <속성 이름 = "sqlsessionaltorybeanname"value = "sqlsessessicatory2"/</bean> </bean> 스코프 = "프로토 타입"> <생성자-arg index = "0"ref = "sqlsessionfactory2"/> </bean> <aop : config> <aop : pointcut id = "appservice"expression = "execution (*com.isea533.mybatis.service ..*service*.*(..))") ")") "). PointCut-Ref = "AppService"/> </aop : config> <tx : adceation id = "txadvice2"transaction-manager = "transactionmanager2"> <tx : attributes> <tx : method name = "*"read-only = "true"/> </tx : </tx : <bean id = "transactionmanager2 ref = "DataSourcesLave"/> </bean> </beans>여기서 <tx : method name = "*"read folly = "true"/>은 읽기 전용이라는 점에 유의해야합니다. 슬레이브 라이브러리가 아닌 경우 기본 라이브러리에 따라 구성 할 수 있습니다.
다음 코드에서 :
<ean> <property name = "basepackage"value = "com.isea533.maper"/> <속성 이름 = "sqlsessionfactorybeanname"value = "sqlsessionfactory2"/> </bean>
sqlsessionfactorybeanname을 통해 다른 sqlsessionfactory를 지정해야합니다.
config.properties
# 데이터베이스 구성 -Mas com.mysql.jdbc.driverslave.jdbc.url = jdbc : mysql : //192.168.1.22 : 3306/testslave.jdbc.user = rootslave.jdbc.password = jj
Mapper 사용
이것은 마스터 및 노예 상황을 위해 설정됩니다. 두 구성 스캔 매퍼는 동일하므로 직접 주입 할 수 없으므로 아래의 번거로운 방법을 통해 주입해야합니다.
@ServicePublic Class Demoservice {Private CountryMapper WriteMapper; 개인 국가 내장 리드 메이프; @Resource (name = "sqlsessionmaster") public void setwriteMapper (sqlsession sqlsession) {this.writeMapper = sqlsession.getMapper (countryMapper.class); } @Resource (name = "sqlsessionsLave") public void setReadMapper (sqlSession sqlSession) {this.ReadMapper = sqlSession.getMapper (countryMapper.class); } public int save (국가 국가) {return writemapper.insert (국가); } public list <country> selectPage (int pagenum, int pagesize) {pagehelper.startPage (pagenum, pagesize); return readmapper.select (null); }}sqlsession은 이름으로 구별 될 수 있으므로 SQLSESSION에서 Mapper를 얻습니다.
또한 동일한 트랜잭션에서 쓰고 읽을 때 고려해야 할 경우 트랜잭션의 최신 데이터를 읽을 수 있도록 동일한 writeMapper를 사용해야합니다.
위는 주인과 노예의 상황입니다.
라이브러리 파티션의 경우 다른 매퍼가 다른 패키지 아래에 있으므로 @Resource 또는 @autowired를 사용하여 Mapper를 직접 주입 할 수 있으며 SQLSESSION을 통해이를 얻을 필요가 없습니다.
이 기사는 여러 데이터 소스에 대한 참조 일뿐입니다. 실제로 적용 할 때 자신의 상황에 따라 고려하십시오.
앞으로 여가 시간을 사용 하여이 기사를 기반으로 데이터 소스를 자동으로 전환 할 수있는 플러그인과 위의 두 개의 관련 링크를 MySQL 여러 데이터 소스에 대한 플러그인을 개발할 것입니다. 나는이 분야의 실제 응용 프로그램에 익숙하지 않기 때문에 모든 사람들이 자신의 솔루션을 공유하기 위해 메시지를 남기도록 환영합니다. 이것에 대해 알수록 일반 데이터 소스 스위칭 플러그인을 개발할 가능성이 높아집니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.