샤딩 실습 (ShardingSphere)

2025. 6. 15. 20:47·CS/데이터베이스

1. 다양한 샤딩 솔루션들

샤딩 기법을 정리해보면 크게 3가지 유형으로 나눠지게 된다.

 

1.1. DB에서 처리

지난 포스팅에서 다뤘던 MongoDB, Cassandra의 경우가 이에 해당한다.
물론 NoSQL뿐만 아니라 RDBMS에서도 이러한 샤딩 기능을 이용할 수 있는 방법들이 존재한다.

 

ex) Spider, MySQL Fabric, PostgreSQL Citus 등

 

1.2. 애플리케이션 서버에서 처리

DB에서 샤딩을 하게 된다면 특정 DBMS 종속적이게 된다는 단점이 생기게 된다. 이에 애플리케이션 서버에서 샤딩 로직을 구현하는 방법이 있다.

 

Spring의 경우 DataSource 설정을 직접 커스텀하여 사용하는 사례를 찾아 볼 수 있었다.

 

우아한 형제의 DB 샤딩 사례: https://techblog.woowahan.com/2687/
 

DB분산처리를 위한 sharding | 우아한형제들 기술블로그

소개 저희는 신사업부문에서 Thiiing(띠잉)서비스를 만들고 있는 송재욱/전병두입니다. 이번에는 두 명이 함께 기술블로그를 작성했습니다. :) 서비스 오픈전에 아름다운 J곡선 그래프를 바라는

techblog.woowahan.com

 

이외에도 별도의 로직 구현 없이 비교적 편하게 사용할 수 있는 방법 또한 존재한다.

 

ex) Hibernate Shards, Shardingsphere-jdbc 등

 

1.3. 플랫폼 단위로 처리

마지막으로 샤딩에 대한 책임을 별도로 분리할 수 있게 플랫폼 단위로 샤딩을 구현하는 방법이 있다. 샤딩 관리에 대한 부담을 줄이고 어플리케이션 로직에 집중할 수 있는 장점이 있다.

 

ex) Shardingsphere-proxy, Spock proxy, Gizzard, Cubrid shard 등

 


 

2. ShardingSphere

애플리케이션을 통해 샤딩 실습을 하기 위해 자료 검색을 하던 도중 ShardingSphere 관련 내용을 흔하게 접할 수 있었다.

 

 

https://github.com/apache/shardingsphere
 

GitHub - apache/shardingsphere: Empowering Data Intelligence with Distributed SQL for Sharding, Scalability, and Security Across

Empowering Data Intelligence with Distributed SQL for Sharding, Scalability, and Security Across All Databases. - apache/shardingsphere

github.com

 

 

ShardingSphere는 데이터베이스 샤딩, 데이터 복제, 트랜잭션 관리 등을 지원하는 Apache의 오픈소스로서 대규모 데이터베이스 환경에서 데이터의 분산 처리 및 관리의 복잡성을 줄이기 위해 설계되었다.

 

앞서 언급한 솔루션 중 Shardingsphere-jdbc는 애플리케이션 레벨의 샤딩을,

 

 

ShardingSphere-proxy는 플랫폼 기반의 샤딩을 지원한다.

 

 

 

이제 ShardingSphere의 특징을 간략하게 알아보도록 하자.

2.1. SQL 처리

 

ShardingSphere는 다음과 같이 분산된 DB, 테이블을 세 개의 독립된 솔루션을 통해 하나의 Logic Table로서 접근 가능하도록 한다.

 

 

Sharding JDBC는 자바 어플리케이션 위에서 JDBC 형태로 동작한다. Application의 비즈니스 로직에 따라 테이블 정보가 포함된 SQL을 실행하면 다음의 처리를 거쳐 DB에 접근한다.

 

1. SQL Parse: SQL문을 형태소 단위로 분해
2. Query Optimize:분해한 SQL문을 최적화
3. SQL Route:샤딩 룰, 샤딩 키등을 분석해 대상 DB, TABLE 선정
4. SQL Rewrite:선정 된 DB, TABLE에 기반하여 SQL문 재작성
5. SQL Execute:재작성된 SQL문 실행
6. Result Merge:각 SQL문 결과들을 Merge하여 하나의 테이블에 접근한 것 같은 통합된 ResultSet을 제공

 

2.2. Paging Dialect

Paging Dialect는 데이터베이스에서 페이징(paging) 기능을 지원하기 위한 쿼리 작성 방식을 정의하는 기능을 말한다.

 

 

ShardingSphere는 다수의 데이터 노드들로부터 결과를 취합하고 정렬하는 다양한 Paging Dialect 기능 또한 지원한다.

 

 


 

3. 실습

이제 본격적으로 ShardingSphere을 이용해서 어플리케이션 레벨의 샤딩을 구현해보고자 한다. 실습에는 MySQL 컨테이너 3대와 Spring 어플리케이션을 사용했다.

 

종속성 추가

먼저 종속성인데 인터넷에 존재하는 많은 자료들이 현재 안되는 경우가 많아서 꽤나 애먹었다. 특히 shardingsphere-jdbc의 경우 설정 yml을 로드해서 클래스를 생성하는데, 관련 종속성이 맞지 않아 실패하는 경우가 많았다.

 

implementation 'org.apache.shardingsphere:shardingsphere-jdbc:5.5.0'

 

 

repository에서 버전을 제대로 확인하도록 하자.

 

https://mvnrepository.com/artifact/org.apache.shardingsphere/sha rdingsphere-jdbc

 

application.yml

ShardingSphere를 통해 데이터베이스와 통신하기 때문에 기존의 datasource 설정을 그대로 사용하지 않는다.

 

spring:
  datasource:
    driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
    url: jdbc:shardingsphere:classpath:sharding.yml
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect

 

sharding.yml

dataSources:
  ds0:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3307/db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=UTF-8
    username: user
    password: 1234
  ds1:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3308/db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=UTF-8
    username: user
    password: 1234
  ds2:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3309/db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=UTF-8
    username: user
    password: 1234

rules:
  - !SHARDING
    tables: # 샤딩할 테이블
      t_order:
        actualDataNodes: ds${0..2}.t_order
        keyGenerateStrategy:
          column: order_id
          keyGeneratorName: snowflake

    defaultDatabaseStrategy: # 데이터베이스 샤딩 전략
      standard:
        shardingColumn: order_id
        shardingAlgorithmName: database_inline

    defaultTableStrategy: # 테이블 샤딩 전략
      none:

    shardingAlgorithms: # 샤딩 알고리즘
      database_inline:
        type: INLINE
        props:
          algorithm-expression: ds${order_id % 3}

    keyGenerators: # 키 생성기
      snowflake:
        type: SNOWFLAKE
        props:
          worker-id: 123

props:
  sql-show: true

 

  • dataSources: 샤드로 사용할 데이터베이스
  • shardingAlgorithms: MOD, HASH_MOD, INLINE 등
  • keyGenerators: SNOWFLAKE, UUID

 

다음과 같이 데이터베이스 또는 테이블 간의 샤딩 전략을 세울 수 있으며, 엔티티의 키 생성 또한 제공받을 수 있다.

단, 키 전략 사용시 엔티티 ID에 IDENTITY 전략을 사용해야 한다.

 

@Getter
@NoArgsConstructor
@Entity
@Table(name = "t_order")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "order_id")
    private Long orderId;

    @Column(name = "product_name")
    private String productName;

    public Order(String productName) {
        this.productName = productName;
    }

}

 

Order 생성

API 요청시에 다음과 같이 Logical SQL과 Actual SQL가 분리되어 출력되는 것을 확인할 수 있다.

 

 

전체 Order 조회

전체 Order 조회시에는 3개의 데이터 노드에 전체 조회 쿼리를 실행하는 것을 확인할 수 있다.

 

 

 

 

'CS > 데이터베이스' 카테고리의 다른 글

Materialized View  (3) 2025.08.03
리플리케이션 실습  (0) 2025.06.29
리플리케이션  (0) 2025.06.29
유일키 생성 전략  (1) 2025.06.15
파티셔닝과 샤딩  (0) 2025.06.15
'CS/데이터베이스' 카테고리의 다른 글
  • 리플리케이션 실습
  • 리플리케이션
  • 유일키 생성 전략
  • 파티셔닝과 샤딩
nicky777
nicky777
  • nicky777
    Nicky Dev
    nicky777
  • 전체
    오늘
    어제
    • 분류 전체보기 (19)
      • Project (9)
        • 티켓핑 (9)
      • TroubleShooting (3)
      • Programming (0)
        • Java (0)
        • Spring (0)
      • CS (7)
        • 데이터베이스 (6)
        • 네트워크 (1)
        • 운영체제 (0)
        • 자료구조 (0)
      • 회고 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • Contact
  • 인기 글

  • 태그

    리플리케이션
    샤딩
    유일키 생성 전략
    materialized view
    HTTP
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
nicky777
샤딩 실습 (ShardingSphere)
상단으로

티스토리툴바