Java java지도 시간 데이터베이스 읽기-쓰기 분리를 구현하는 Spring의 예

데이터베이스 읽기-쓰기 분리를 구현하는 Spring의 예

Jan 24, 2017 am 10:14 AM

현재 대규모 전자상거래 시스템의 대부분은 마스터 데이터베이스와 다중 슬레이브 데이터베이스인 데이터베이스 수준의 읽기-쓰기 분리 기술을 사용합니다. 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&#39;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()
로그인 후 복사

위의 정의를 보면 몇 가지 아이디어가 있습니까?

데이터베이스 읽기-쓰기 분리를 구현하는 Spring의 예

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을 입력하고 로그인하여 확인하세요. 효과

Spring 实现数据库读写分离的示例

Spring 实现数据库读写分离的示例

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 PHP 중국어 웹사이트를 지지해 주시길 바랍니다.

데이터베이스 읽기-쓰기 분리를 구현한 Spring 예제에 대한 더 많은 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까? 카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까? Mar 17, 2025 pm 05:44 PM

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까? Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까? Mar 17, 2025 pm 05:35 PM

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

Java에서 기능 프로그래밍 기술을 어떻게 구현할 수 있습니까? Java에서 기능 프로그래밍 기술을 어떻게 구현할 수 있습니까? Mar 11, 2025 pm 05:51 PM

이 기사는 Lambda 표현식, 스트림 API, 메소드 참조 및 선택 사항을 사용하여 기능 프로그래밍을 Java에 통합합니다. 간결함과 불변성을 통한 개선 된 코드 가독성 및 유지 관리 가능성과 같은 이점을 강조합니다.

캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까? 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까? Mar 17, 2025 pm 05:43 PM

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까? 고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까? Mar 17, 2025 pm 05:46 PM

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

비 블로킹 I/O에 Java의 NIO (새로운 입력/출력) API를 어떻게 사용합니까? 비 블로킹 I/O에 Java의 NIO (새로운 입력/출력) API를 어떻게 사용합니까? Mar 11, 2025 pm 05:51 PM

이 기사에서는 선택기와 채널을 사용하여 단일 스레드와 효율적으로 처리하기 위해 선택기 및 채널을 사용하여 Java의 NIO API를 설명합니다. 프로세스, 이점 (확장 성, 성능) 및 잠재적 인 함정 (복잡성,

적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까? 적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까? Mar 17, 2025 pm 05:45 PM

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

네트워크 통신에 Java의 Sockets API를 어떻게 사용합니까? 네트워크 통신에 Java의 Sockets API를 어떻게 사용합니까? Mar 11, 2025 pm 05:53 PM

이 기사는 네트워크 통신을위한 Java의 소켓 API, 클라이언트 서버 설정, 데이터 처리 및 리소스 관리, 오류 처리 및 보안과 같은 중요한 고려 사항에 대해 자세히 설명합니다. 또한 성능 최적화 기술, i

See all articles