2014年7月10日 星期四

透過 Apache jClouds 操作本地檔案系統的 Blob Store

Apache jClouds 是一個可以支援很多不同雲端基礎建設的開源函式庫
其中可以利用它的 Blob Store 的介面,來操作各家雲端基礎建設的儲存服務。
不過其實它也有提供非雲端基礎建設的實作,讓使用者可以適度地把一些沒有要放上雲端的東西,透過它的介面存放在本地的檔案系統。

以 Blob Store 來說,就可以透過 org.jclouds.api/filesystem [1] 這個實作的套件來達成
這個套件如果要用 Maven 設定的話,需要加上的內容如下:
<dependency>
  <groupId>org.apache.jclouds.api</groupId>
  <artifactId>filesystem</artifactId>
  <version>1.7.3</version>
</dependency>

而使用的方法大體上其實跟一般 jClouds 操作差不多,只不過不需要使用者驗證的步驟。
另外在初始化 BlobStore 時,可以透過 Properties 來設定存放的根目錄。

// Initiate the properties for specifying the storage path to the local file system.
Properties properties = new Properties();
properties.setProperty(
    FilesystemConstants.PROPERTY_BASEDIR, 
    "/storage");

// Initiate the instance of blob store.
BlobStore blobStore = ContextBuilder.newBuilder("filesystem")
               .overrides(properties)
               .buildView(BlobStoreContext.class)
               .getBlobStore();

// Initiate a file for tranfering through jclouds.
File file = new File("/home/user/test_file");

// Create a container if it was not created.
blobStore.createContainerInLocation(null, "folder_name");

// Initiate a blob according to the file which attends to be transfered.
Blob blob = blobStore.blobBuilder("blob_name")
          .payload(file)
          .contentLength(file.length())
          .build();

blobStore.putBlob("folder_name", blob);

以上面的例子來說,一開始屬性設定中,PROPERTY_BASEDIR 設定的路徑是 /storage
然後要上傳 Blob 時設定 container 名稱為 folder_name、要上傳的 blog 名稱則為 blob_name
因此最後執行完成後,會在本地的檔案系統中產生 /storage/folder_name/blob_name 這個檔案,而檔案內容會跟 /home/user/test_file 一樣。

參考資料:
1、File System: Getting Started Guide

沒有留言: