jcloud:我应该保留BlobStoreContext实例吗?

时间:2013-09-24 12:26:54

标签: rackspace cloudfiles jclouds

我有以下方法允许我将文件上传到Rackspace CloudFiles上的容器:

/**
 * Uploads a file to the storage.
 *
 * @param     f the <code>File</code> which is to be uploaded to the storage.
 * @param     fileContainer a <code>String</code> representing the container
 *            which the provided <code>File</code> is to be uploaded to.
 * @throws    StorageException if an attempt to upload the provided file to
 *            the storage failed.
 */
public static void upload(File file, String fileContainer) throws StorageException {

    if (!file.exists()) {
        throw new StorageException("The file '" + file.getName() + "' does not exist.");
    }

    try {

        BlobStoreContext cb = ContextBuilder.newBuilder("cloudfiles-uk")
            .credentials(USERNAME, PASSWORD)
            .buildView(BlobStoreContext.class);            

        Blob blob = cb.getBlobStore().blobBuilder(file.getName())
            .payload(file)
            .build();

        cb.getBlobStore().putBlob(fileContainer, blob);

    } catch (Exception e) {
        throw new StorageException(e);
    }
}

现在,每次调用方法时,我都会创建一个新的上下文。据我所知,代码只会在第一次调用时进行身份验证,并从那里使用在第一次身份验证期间发出的密钥用于所有后续调用。但是,我不确定这是正确的吗?如果我抛弃BlobStoreContext实例并在每次调用upload()时实例化一个新实例,我将重新进行身份验证吗?保留BlobStoreContext实例会更好吗?

1 个答案:

答案 0 :(得分:1)

现在您已拥有代码,您将在每次调用“上传”功能时重新验证。 相反,您可能想要创建一个全局上下文变量,调用身份验证函数来设置您的凭据,然后在上传函数中使用上下文。

见这个例子:

https://github.com/jclouds/jclouds-examples/blob/master/rackspace/src/main/java/org/jclouds/examples/rackspace/Authentication.java