Spring AOP, MySQL 마스터 슬레이브 구성은 읽기 및 쓰기 분리를 실현합니다. 다음으로, 다음 작업을 용이하게하기 위해 자신의 구성 프로세스 및 문제가 발생합니다. 나는 또한 친구들을 돕기를 희망합니다.
1. 스프링 AOP 차단 메커니즘을 사용하여 데이터 소스의 동적 선택을 실현하십시오.
import java.lang.annotation.elementtype; Java.lang.annotation.target import; java.lang.annotation.trention import; java.lang.annotation.retentionpolicy import; /** * 런타임 * 컴파일러는 클래스 파일에 주석을 기록하고 VM은 런타임에 주석을 유지하므로 반사적으로 읽을 수 있습니다. * @Author Yangguang * */ @retention (rendentionpolicy.runtime) @target (elementtype.method) public @interface dataSource {String value (); } 3. Spring의 AbstroutingDatasource를 사용하여 여러 데이터 소스의 문제를 해결하십시오.
org.springframework.jdbc.datasource.lookup.abstractroutingdatasource; 공개 클래스 choneatasource는 AbsTractroutingDatasource를 확장합니다. }}
4. 스레드 안전 문제를 해결하기 위해 ThreadLocal을 사용하십시오
공개 클래스 handledataSource {public static final roodlocal <string> holder = new ThreadLocal <string> (); public static void putdatasource (String DataSource) {holder.set (dataSource); } public static string getDatasource () {return holder.get (); }}5. AOP를 통해 액세스하고 스프링 구성 파일에 구성되어 있으므로 AOP 주석이 사용되지 않습니다.
import java.lang.reflect.method; import org.aspectj.lang.joinpoint; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.free; import org.aspectj.lang.annotation.pointcut; import org.aspectj.lang.reflect.methodsignature; org.springframework.stereotyp.component import; //@Aspect //@component public class datasourceaspect {//@pointcut ( "execution (*com.apc.cms.service.*.*(..))") public void pointcut () {}; // @Before (value = "pointCut ()") public void wefore (joinpoint point) {Object target = point.getTarget (); System.out.println (target.toString ()); 문자열 메소드 = point.getSignature (). getName (); System.out.println (메소드); class <?> [] classz = target.getClass (). getInterfaces (); class <?> [] parametertypes = (((methodsignature) point.getSignature ()) .getMethod (). getParameterTypes (); try {method m = classz [0] .getMethod (메소드, ParameterTypes); System.out.println (m.getName ()); if (m! = null && m.isannotationPresent (dataSource.class)) {dataSource data = m.getAntation (dataSource.class); handledatasource.putdatasource (data.value ()); }} catch (예외 e) {e.printstacktrace (); }}}6. ApplicationContext.xml 구성
<!-메인 라이브러리 데이터 소스-> <bean id = "writedatasource"Destroy-method = "close"> <property name = "driver class"value = "com.mysql.jdbc.driver"/> <property name = "jdbcurl"value = "jdbc : mysql : //172.14.6 : 3306/cpp? 이름 = "username"value = "root"/> <property name = "password"valeas = "root"/> <property name = "partitionCount"value = "4"/> <property name = "releaseHelperThreads"value = "3"/> <속성 이름 = "arcireIncrement"value = "2"/> <propertynectionspartition "value ="maxConnectionSpartiton " value = "20"/> <property name = "idlemaxageinseconds"value = "60"/> <property name = "idleconnectiontestesteperiodinseconds"value = "60"/> <property name = "ploolavailabilitythreshold"value = "5"/> </bean> <!-라이브러리 데이터 소스에서-> bean id = "readdatoucce" "readdatoucce"< 이름 = "driver class"value = "com.mysql.jdbc.driver"/> <property name = "jdbcurl"value = "jdbc : mysql : //172.22.14.7 : 3306/cpp? autoreconnect = true"/> <property "/> 이름 = "PartitionCount"value = "4"/> <속성 이름 = "releaseHelperThreads"value = "3"/> <속성 이름 = "arcireIncrement"value = "2"/> <property name = "maxConnectionsPerPartition"value = "40"/> <property name = "minConnectionSperPartition"value "20" "20" "60" "60" "60" <property name = "idleconnectionTestPeriodinseconds"value = "60"/> <속성 이름 = "foolAvailabilitythreshold"value = "5"/> </bean> <!-트랜잭션 관리자, 트랜잭션 관리-> <bean id = "transactionManager"> <property name = "datasource"ref = "dataSource"/bean> <! <context : Annotation-Config /> <!-Enale 구성 요소 스캔 (맵퍼 스캐닝을 활성화하지 않는다고 조심하십시오!)-> <context : component-scan base-package = "com.apc.cms.persistence.rdbms" /> <context : context : com.apc.cms "> 컨텍스트 : 컨텍스트 : 포함. expression = "org.springframework.steretype.component" /> < /context : component-scan> <context : component-scan base-package = "com.apc.cms.auth" /> <!-주석을 사용한 트랜잭션 경계 활성화-> <TX : Annotation-Driven /> <!-정의 <bean < id = "sqlsessionFactory"> <속성 이름 = "dataSource"ref = "dataSource" /> <property name = "intevaliasespackage"value = "com.apc.cms.model.domain" /> < /bean> <!-맵퍼에 대한 스캔-> <bean> <propertence name = "value"= "value" 이름 = "sqlsessionFactory"ref = "sqlsessionFactory"/> </bean> <bean id = "dataSource"> <property name = "targetdatasources"> <map key-type = "java.lang.string"> <!-write-> <alturef "value-ref ="writedatasource "/> <retting"writedatasource "> <! value-Ref = "readdatasource"/> </map> </map> </property> <property name = "defaultTargetDataSource"ref = "writeDatasource"/> </bean> <!-자동 프록시 기능-> <aop : agage-autopproxy proxy-target class = "true"/> <! id = "dataSourCeaspect"/> <aop : config> <aop : agage id = "c"ref = "dataSourceaspect"> <aop : pointcut id = "tx"expression = "execution (*com.apc.cms.service .. </aop : config> <!-데이터베이스 주석을 구성합니다
7. 주석을 사용하여 데이터 소스를 동적으로 선택하고 라이브러리를 읽고 각각 라이브러리를 작성하십시오.
@datasource ( "쓰기") public void update (사용자 사용자) {usermapper.update (user); } @datasource ( "읽기") 공개 문서 getDocById (long id) {return documentMapper.getById (id); } 테스트 쓰기 작동 : 응용 프로그램을 통해 데이터를 수정하고 기본 라이브러리 데이터를 수정할 수 있습니다. 슬레이브 라이브러리의 데이터가 동기식으로 업데이트되었으므로 정의 된 쓰기 작업은 모두 라이브러리에 기록됩니다.
테스트 읽기 작동 : 백그라운드에서 슬레이브 데이터베이스 데이터를 수정하고, 기본 데이터베이스의 데이터가 수정되지 않았는지 확인하고 응용 프로그램 페이지에서 새로 고침을 취득한 후 슬레이브 데이터베이스의 데이터가 읽는지 확인하므로 읽기 및 쓰기 분리가 정상임을 의미합니다.
발생하는 문제 요약 :
질문 1 : 프로젝트는 Maven 프로젝트이며 Spring AOP 메커니즘이 사용됩니다. 스프링의 핵심 JAR 패키지 외에도 사용해야하는 JAR 패키지는 Sagne.jar, SucleJweaver.jar 및 Aopalliance.jar입니다. 프로젝트에서 POM을 확인하고 종속성 패키지가 누락되었는지 확인하십시오. 로컬 리포지토리에는 이러한 항아리가 없으므로 JAR 패키지 다운로드를 제공하고 Maven으로 구성하고 자동으로 업데이트 할 수있는 Maven Central 라이브러리를 찾으십시오.
<repository> <id> nexus </id> <name> nexus </name> <url> http://repository.sonatype.org/content/groups/public/ </url> <layout> default </layout> </repository>
프로젝트 구성에 의존하는 항아리는 주로이 두 가지가 누락되었습니다.
<pectionency> <groupId> 종면 </groupId> <artifactID> AspectJrt </artifactid> <bersion> 1.5.4 </version> </fectionency> <pectionency> <groupId> aggej </groupId> <artifactID> 측면 jweaver </artifactid> <5.4 </decivency> lt;/dependency>
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.