2

我有以下方法允许我将文件上传到 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 实例会更好吗?

4

1 回答 1

1

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

看这个例子:

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

于 2013-09-24T15:34:03.743 回答