Class ShardingKeyDataSourceAdapter

java.lang.Object
org.springframework.jdbc.datasource.DelegatingDataSource
org.springframework.jdbc.datasource.ShardingKeyDataSourceAdapter
All Implemented Interfaces:
Wrapper, CommonDataSource, DataSource, InitializingBean

public class ShardingKeyDataSourceAdapter extends DelegatingDataSource
An adapter for a target DataSource, designed to apply sharding keys, if specified, to every standard #getConnection call, returning a direct connection to the shard corresponding to the specified sharding key value. All other methods simply delegate to the corresponding methods of the target DataSource.

The target DataSource must implement the createConnectionBuilder() method; otherwise, a SQLFeatureNotSupportedException will be thrown when attempting to acquire shard connections.

This adapter needs to be configured with a ShardingKeyProvider callback which is used to get the current sharding keys for every #getConnection call, for example:

 ShardingKeyDataSourceAdapter dataSourceAdapter = new ShardingKeyDataSourceAdapter(dataSource);
 dataSourceAdapter.setShardingKeyProvider(() -> dataSource.createShardingKeyBuilder()
     .subkey(SecurityContextHolder.getContext().getAuthentication().getName(), JDBCType.VARCHAR).build());
 
Since:
6.1.2
Author:
Mohamed Lahyane (Anir), Juergen Hoeller
See Also:
  • Constructor Details

    • ShardingKeyDataSourceAdapter

      public ShardingKeyDataSourceAdapter(DataSource dataSource)
      Create a new instance of ShardingKeyDataSourceAdapter, wrapping the given DataSource.
      Parameters:
      dataSource - the target DataSource to be wrapped
    • ShardingKeyDataSourceAdapter

      public ShardingKeyDataSourceAdapter(DataSource dataSource, ShardingKeyProvider shardingKeyProvider)
      Create a new instance of ShardingKeyDataSourceAdapter, wrapping the given DataSource.
      Parameters:
      dataSource - the target DataSource to be wrapped
      shardingKeyProvider - the ShardingKeyProvider used to get the sharding keys
  • Method Details