데이터베이스 읽기-쓰기 분리를 구현하는 Spring의 예
현재 대규모 전자상거래 시스템의 대부분은 마스터 데이터베이스와 다중 슬레이브 데이터베이스인 데이터베이스 수준의 읽기-쓰기 분리 기술을 사용합니다. Master 라이브러리는 데이터 업데이트와 실시간 데이터 쿼리를 담당하고, Slave 라이브러리는 물론 비실시간 데이터 쿼리를 담당합니다. 실제 애플리케이션에서는 데이터베이스가 더 많이 읽고 더 적게 쓰기 때문에(데이터를 읽는 빈도는 높고 데이터를 업데이트하는 빈도는 상대적으로 낮음) 일반적으로 데이터를 읽는 데 시간이 오래 걸리고 데이터베이스 서버의 CPU를 많이 차지합니다. , 그래서 사용자 경험에 영향을 미칩니다. 우리의 일반적인 접근 방식은 기본 데이터베이스에서 쿼리를 추출하고, 여러 슬레이브 데이터베이스를 사용하고, 로드 밸런싱을 사용하여 각 슬레이브 데이터베이스에 대한 쿼리 부담을 줄이는 것입니다.
읽기-쓰기 분리 기술 사용의 목표: 마스터 라이브러리에 대한 부담을 효과적으로 줄이고 데이터 쿼리에 대한 사용자 요청을 다른 슬레이브 라이브러리에 분산시켜 시스템의 견고성을 보장합니다. 읽기-쓰기 분리를 채택하게 된 배경을 살펴보자.
웹사이트의 비즈니스가 지속적으로 확장되고, 데이터가 지속적으로 증가하고, 사용자가 점점 많아지면서 데이터베이스나 SQL 최적화와 같은 전통적인 방법이 기본적으로 증가하고 있습니다. 충분하지 않은 경우에는 읽기와 쓰기를 분리하는 전략을 사용하여 현상을 변경할 수 있습니다.
구체적으로 개발 시 읽기와 쓰기를 어떻게 쉽게 분리할 수 있나요? 현재 일반적으로 사용되는 두 가지 방법이 있습니다.
1 첫 번째 방법은 가장 일반적으로 사용되는 방법으로 정의합니다. 2 데이터베이스 연결, 하나는 MasterDataSource이고 다른 하나는 SlaveDataSource입니다. 데이터를 업데이트할 때 MasterDataSource를 읽고, 데이터를 쿼리할 때 SlaveDataSource를 읽습니다. 이 방법은 매우 간단하므로 자세히 설명하지 않겠습니다.
2 동적 데이터 소스 전환의 두 번째 방법은 프로그램이 실행될 때 데이터 소스를 프로그램에 동적으로 엮어 메인 라이브러리 또는 슬레이브 라이브러리에서 읽도록 선택하는 것입니다. 사용되는 주요 기술은 주석, Spring AOP, 리플렉션입니다. 구현 방법은 아래에서 자세히 소개하겠습니다.
구현 방법을 소개하기 전에 먼저 필요한 지식을 준비합니다. Spring의 AbstractRoutingDataSource 클래스
AbstractRoutingDataSource 클래스는 Spring 2.0 이후에 추가되었습니다. 먼저 AbstractRoutingDataSource의 정의를 살펴보겠습니다.
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}
AbstractRoutingDataSource는 DataSource의 하위 클래스인 AbstractDataSource를 상속합니다. DataSource는 javax.sql의 데이터 소스 인터페이스로 다음과 같이 정의됩니다.
public interface DataSource extends CommonDataSource,Wrapper { /** * <p>Attempts to establish a connection with the data source that * this <code>DataSource</code> object represents. * * @return a connection to the data source * @exception SQLException if a database access error occurs */ Connection getConnection() throws SQLException; /** * <p>Attempts to establish a connection with the data source that * this <code>DataSource</code> object represents. * * @param username the database user on whose behalf the connection is * being made * @param password the user's password * @return a connection to the data source * @exception SQLException if a database access error occurs * @since 1.4 */ Connection getConnection(String username, String password) throws SQLException; }
DataSource 인터페이스는 두 가지 메소드를 정의하며 둘 다 데이터베이스 연결을 얻습니다. AbstractRoutingDataSource가 DataSource 인터페이스를 구현하는 방법을 살펴보겠습니다.
public Connection getConnection() throws SQLException { return determineTargetDataSource().getConnection(); } public Connection getConnection(String username, String password) throws SQLException { return determineTargetDataSource().getConnection(username, password); }
분명히 연결을 얻기 위해 고유한determinTargetDataSource() 메서드를 호출합니다. DefineTargetDataSource 메소드는 다음과 같이 정의됩니다:
protected DataSource determineTargetDataSource() { 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 new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]"); } return dataSource; }
우리가 가장 우려하는 것은 다음 2개의 문장입니다:
Object lookupKey = determineCurrentLookupKey(); DataSource dataSource = this.resolvedDataSources.get(lookupKey);
determinCurrentLookupKey 메소드는 LookupKey를 반환하고,solvedDataSources 메소드는 LookupKey를 기반으로 Map에서 데이터 소스를 가져옵니다. ResolvedDataSources 및 DetermedCurrentLookupKey는 다음과 같이 정의됩니다.
private Map<Object, DataSource> resolvedDataSources; protected abstract Object determineCurrentLookupKey()
위의 정의를 보면 몇 가지 아이디어가 있습니까?
AbstractRoutingDataSource를 상속하고 Map 키, 마스터 또는 슬레이브를 반환하는 해당 DefineCurrentLookupKey() 메서드를 구현하는 DynamicDataSource 클래스를 작성하고 있습니다.
글쎄, 얘기를 너무 많이 해서 좀 심심해서 어떻게 구현하는지 살펴보겠습니다.
우리가 사용하고 싶은 기술은 위에서 언급했습니다. 먼저 주석의 정의를 살펴보겠습니다.
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DataSource { String value(); }
또한 구현해야 합니다. Spring의 추상화 AbstractRoutingDataSource 클래스는 다음과 같은determinCurrentLookupKey 메소드를 구현합니다:
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { // TODO Auto-generated method stub return DynamicDataSourceHolder.getDataSouce(); } } public class DynamicDataSourceHolder { public static final ThreadLocal<String> holder = new ThreadLocal<String>(); public static void putDataSource(String name) { holder.set(name); } public static String getDataSouce() { return holder.get(); } }
DynamicDataSource의 정의에서 우리에게 필요한 DynamicDataSourceHolder.getDataSouce() 값을 반환합니다. 프로그램에서 실행하려면 DynamicDataSourceHolder.putDataSource() 메서드를 호출할 때 값을 할당하세요. 다음은 우리 구현의 핵심 부분이며, DataSourceAspect는 다음과 같이 정의됩니다:
public class DataSourceAspect { public void before(JoinPoint point) { Object target = point.getTarget(); String method = point.getSignature().getName(); Class<?>[] classz = target.getClass().getInterfaces(); Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()) .getMethod().getParameterTypes(); try { Method m = classz[0].getMethod(method, parameterTypes); if (m != null && m.isAnnotationPresent(DataSource.class)) { DataSource data = m .getAnnotation(DataSource.class); DynamicDataSourceHolder.putDataSource(data.value()); System.out.println(data.value()); } } catch (Exception e) { // TODO: handle exception } } }
테스트를 용이하게 하기 위해 2개를 정의했습니다. 데이터베이스, 상점 시뮬레이션 마스터 라이브러리, 테스트는 슬레이브 라이브러리를 시뮬레이션합니다. 상점과 테스트의 테이블 구조는 동일하지만 데이터가 다릅니다. 데이터베이스 구성은 다음과 같습니다.
<bean id="masterdataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/shop" /> <property name="username" value="root" /> <property name="password" value="yangyanping0615" /> </bean> <bean id="slavedataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" /> <property name="username" value="root" /> <property name="password" value="yangyanping0615" /> </bean> <beans:bean id="dataSource" class="com.air.shop.common.db.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <!-- write --> <entry key="master" value-ref="masterdataSource"/> <!-- read --> <entry key="slave" value-ref="slavedataSource"/> </map> </property> <property name="defaultTargetDataSource" ref="masterdataSource"/> </beans:bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置SqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:config/mybatis-config.xml" /> </bean>
스프링 구성에 aop 구성 추가
<!-- 配置数据库注解aop --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <beans:bean id="manyDataSourceAspect" class="com.air.shop.proxy.DataSourceAspect" /> <aop:config> <aop:aspect id="c" ref="manyDataSourceAspect"> <aop:pointcut id="tx" expression="execution(* com.air.shop.mapper.*.*(..))"/> <aop:before pointcut-ref="tx" method="before"/> </aop:aspect> </aop:config> <!-- 配置数据库注解aop -->
다음은 테스트를 용이하게 하기 위해 MyBatis의 UserMapper 정의입니다. library이고 사용자 목록은 슬레이브 라이브러리를 읽습니다.
public interface UserMapper { @DataSource("master") public void add(User user); @DataSource("master") public void update(User user); @DataSource("master") public void delete(int id); @DataSource("slave") public User loadbyid(int id); @DataSource("master") public User loadbyname(String name); @DataSource("slave") public List<User> list(); }
좋아요. Eclipse를 실행하여 효과를 확인하고, 사용자 이름 admin을 입력하고 로그인하여 확인하세요. 효과
위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 PHP 중국어 웹사이트를 지지해 주시길 바랍니다.
데이터베이스 읽기-쓰기 분리를 구현한 Spring 예제에 대한 더 많은 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

많은 응용 프로그램 시나리오에서 정렬을 구현하기 위해 이름으로 이름을 변환하는 솔루션, 사용자는 그룹으로, 특히 하나로 분류해야 할 수도 있습니다.

시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

Redis 캐싱 솔루션은 제품 순위 목록의 요구 사항을 어떻게 인식합니까? 개발 과정에서 우리는 종종 a ... 표시와 같은 순위의 요구 사항을 처리해야합니다.

전자 상거래 플랫폼에서 SKU 및 SPU 테이블의 디자인에 대한 자세한 설명이 기사는 전자 상거래 플랫폼에서 SKU 및 SPU의 데이터베이스 설계 문제, 특히 사용자 정의 판매를 처리하는 방법에 대해 논의 할 것입니다 ...
