GridFS のサポート

MongoDB は、ファイルシステム GridFS 内にバイナリファイルを保存することをサポートしています。Spring Data MongoDB は、ファイルシステムと対話できるように、GridFsOperations (Javadoc) および ReactiveGridFsOperations (Javadoc) インターフェースと、対応する実装である GridFsTemplate および ReactiveGridFsTemplate を提供します。次の例に示すように、MongoDatabaseFactory/ReactiveMongoDatabaseFactory および MongoConverter を渡すことでテンプレートインスタンスを設定できます。

  • 命令的

  • リアクティブ

  • XML

class GridFsConfiguration extends AbstractMongoClientConfiguration {

  // … further configuration omitted

  @Bean
  public GridFsTemplate gridFsTemplate() {
    return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
  }
}
class ReactiveGridFsConfiguration extends AbstractReactiveMongoConfiguration {

  // … further configuration omitted

  @Bean
  public ReactiveGridFsTemplate reactiveGridFsTemplate() {
    return new ReactiveGridFsTemplate(reactiveMongoDbFactory(), mappingMongoConverter());
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
https://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

  <mongo:db-factory id="mongoDbFactory" dbname="database" />
  <mongo:mapping-converter id="converter" />

  <bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
    <constructor-arg ref="mongoDbFactory" />
    <constructor-arg ref="converter" />
  </bean>

</beans>

次の例に示すように、テンプレートを挿入して、保存および取得操作を実行するために使用できるようになりました。

GridFS を使用してファイルを保存する
  • 命令的

  • リアクティブ

class GridFsClient {

  @Autowired
  GridFsOperations operations;

  @Test
  public void storeFileToGridFs() {

    FileMetadata metadata = new FileMetadata();
    // populate metadata
    Resource file = … // lookup File or Resource

    operations.store(file.getInputStream(), "filename.txt", metadata);
  }
}

store(…) 操作は、InputStream、ファイル名、(オプションで) 保存するファイルに関するメタデータ情報を受け取ります。メタデータは任意のオブジェクトにすることができ、GridFsTemplate で構成された MongoConverter によってマーシャリングされます。あるいは、Document を指定することもできます。

class ReactiveGridFsClient {

  @Autowired
  ReactiveGridFsTemplate operations;

  @Test
  public Mono<ObjectId> storeFileToGridFs() {

    FileMetadata metadata = new FileMetadata();
    // populate metadata
    Publisher<DataBuffer> file = … // lookup File or Resource

    return operations.store(file, "filename.txt", metadata);
  }
}

store(…) 操作は、Publisher<DataBuffer>、ファイル名、(オプションで) 保存するファイルに関するメタデータ情報を受け取ります。メタデータは任意のオブジェクトにすることができ、ReactiveGridFsTemplate で構成された MongoConverter によってマーシャリングされます。あるいは、Document を指定することもできます。

MongoDB のドライバーは、AsyncInputStream および AsyncOutputStream インターフェースを使用してバイナリストリームを交換します。Spring Data MongoDB は、これらのインターフェースを Publisher<DataBuffer> に適合させます。Spring のリファレンスドキュメントの DataBuffer の詳細を参照してください。

find(…) または getResources(…) メソッドを使用して、ファイルシステムからファイルを読み取ることができます。まず find(…) メソッドを見てみましょう。Query に一致する単一のファイルまたは複数のファイルを見つけることができます。GridFsCriteria ヘルパークラスを使用してクエリを定義できます。これは、デフォルトのメタデータフィールド ( whereFilename() や whereContentType() など) または whereMetaData() を介したカスタムフィールドをカプセル化するための静的ファクトリメソッドを提供します。次の例は、テンプレートを使用してファイルをクエリする方法を示しています。

GridFsTemplate を使用したファイルのクエリ
  • 命令的

  • リアクティブ

class GridFsClient {

  @Autowired
  GridFsOperations operations;

  @Test
  public void findFilesInGridFs() {
    GridFSFindIterable result = operations.find(query(whereFilename().is("filename.txt")));
  }
}
class ReactiveGridFsClient {

  @Autowired
  ReactiveGridFsTemplate operations;

  @Test
  public Flux<GridFSFile> findFilesInGridFs() {
    return operations.find(query(whereFilename().is("filename.txt")))
  }
}
現在、MongoDB は、GridFS からファイルを取得する際の並べ替え条件の定義をサポートしていません。このため、find(…) メソッドに渡された Query インスタンスで定義された並べ替え条件は無視されます。

GridFs からファイルを読み取るもう 1 つのオプションは、ResourcePatternResolver インターフェースによって導入されたメソッドを使用することです。これらにより、Ant パスをメソッドに渡すことができるため、指定されたパターンに一致するファイルを取得できます。次の例は、GridFsTemplate を使用してファイルを読み取る方法を示しています。

GridFsTemplate を使用したファイルの読み取り
  • 命令的

  • リアクティブ

class GridFsClient {

  @Autowired
  GridFsOperations operations;

  public GridFsResources[] readFilesFromGridFs() {
     return operations.getResources("*.txt");
  }
}
class ReactiveGridFsClient {

  @Autowired
  ReactiveGridFsOperations operations;

  public Flux<ReactiveGridFsResource> readFilesFromGridFs() {
     return operations.getResources("*.txt");
  }
}

GridFsOperations は ResourcePatternResolver を継承し、GridFsTemplate (たとえば) を ApplicationContext に接続して、MongoDB データベースから Spring 構成ファイルを読み取ることができるようにします。

デフォルトでは、GridFsTemplate は最初の GridFS 対話時に GridFSBucket を 1 回取得します。その後、テンプレートインスタンスはキャッシュされたバケットを再利用します。異なるバケットを使用するには、同じ Template インスタンスから Supplier<GridFSBucket> を受け入れるコンストラクターを使用します。