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

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

高洛峰
高洛峰원래의
2017-01-24 10:14:471221검색

현재 대규모 전자상거래 시스템의 대부분은 마스터 데이터베이스와 다중 슬레이브 데이터베이스인 데이터베이스 수준의 읽기-쓰기 분리 기술을 사용합니다. 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으로 문의하세요.