我试图弄清楚在 Google Cloud Store 的 Bucket
中测试 Object
是否存在的最有效方法。
这就是我现在正在做的:
try
{
final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
if (md == null)
{
// do what I need to do here!
}
}
catch (IOException e)
{
L.error(e.getMessage());
}
因为根据文档,如果 GcsFilename
不存在,它会返回 null
。
.
/**
* @param filename The name of the file that you wish to read the metadata of.
* @return The metadata associated with the file, or null if the file does not exist.
* @throws IOException If for any reason the file can't be read.
*/
GcsFileMetadata getMetadata(GcsFilename filename) throws IOException;
在 Bucket
上使用 .list()
并检查 .contains()
听起来很昂贵,但其意图很明确。
我个人认为测试 null
来检查是否存在某些东西是不优雅的,而且不像 GCS_SERVICE.objectExists(fileName);
那样直接,但我想我不'开始设计 GCS 客户端 API。我将在我的 API 中创建一个方法来执行此测试。
是否有更有效(及时)或更自记录的方式来进行此测试?
最佳答案
解决方案
这是我最终得到的工作解决方案:
@Nonnull
protected Class<T> getEntityType() { (Class<T>) new TypeToken<T>(getClass()) {}.getRawType(); }
/**
* purge ObjectMetadata records that don't have matching Objects in the GCS anymore.
*/
public void purgeOrphans()
{
ofy().transact(new Work<VoidWork>()
{
@Override
public VoidWork run()
{
try
{
for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable())
{
final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
if (md == null)
{
ofy().delete().entity(bm);
}
}
}
catch (IOException e)
{
L.error(e.getMessage());
}
return null;
}
});
}
关于google-cloud-storage - 测试对象是否存在于桶中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25160470/