Create a custom MongoTemplate bean using the snippet given below.
package com.alpha.mongodb.sharding.example.configuration;
@Configuration
public class CollectionShardedMongoConfiguration {
@Bean("collectionShardedMongoTemplate")
public MongoTemplate collectionShardedMongoTemplate(
@Autowired MongoDatabaseFactory collectionShardedMongoDbFactory) {
CollectionShardingOptions shardingOptions =
CollectionShardingOptions.withIntegerStreamHints(
IntStream.range(0, 3));
return new CollectionShardedMongoTemplate(
collectionShardedMongoDbFactory(), shardingOptions);
}
}
Implement your entity classes from CollectionShardedEntity. If this is not a feasible approach for you, then you can always register a HintResolutionCallback to ShardingOptions and use it. See the section below to get an example usage of Hint Resolution Callback.
Autowire the collectionShardedMongoTemplate and use it wherever required.
Using Sharding Hint
In order to route the write queries, the entities are supposed to implement from CollectionShardedEntity. But, the find queries can take place with different criterion, with different fields. In order to route the find query to the right collection, sharding hint is used.
import java.util.Optional;
public class TestRepository {
@Autowired
@Qualifier("collectionShardedMongoTemplate")
private MongoTemplate collectionShardedMongoTemplate;
public Optional<TestShardEntity> findById() {
ShardingHintManager.setCollectionHint("3");
return Optional.ofNullable(
collectionShardedMongoTemplate.findById(
"6427b9327a2cad734d5ff051",
TestShardEntity.class));
}
}
If the sharding hint is not set, methods will throw a UnresolvableShardException.
Using HintResolutionCallback
You can extend your entities from CollectionShardedEntity to resolve the sharding hint whenever an entity context is passed to the queries. This can also be done using HintResolution callback which a provides couple of methods to resolve hint.
For an entity that is not extending from CollectionShardedEntity a callback can be registered with Sharding Options by calling ShardingOptions::setHintResolutionCallbacks. If the callbacks are defined as spring beans they are automatically discovered during initializing application context.
@Data
@org.springframework.data.mongodb.core.mapping.Document("TEST1")
@FieldNameConstants
public class TestEntity1 {
@Id
private String id;
@Indexed(unique = true)
private String indexedField;
public static class TestEntity1HintResolutionCallback implements HintResolutionCallback<TestEntity1> {
@Override
public ShardingHint resolveHintForFindContext(Document query, Class<TestEntity1> entityClass) {
return ShardingHint.withCollectionHint("0");
}
@Override
public ShardingHint resolveHintForSaveContext(TestEntity1 entity) {
return ShardingHint.withCollectionHint("0");
}
}
}