如何使用AWS SDK for Ruby v2.0检查simpleDB域是否存在

时间:2015-10-20 23:17:54

标签: ruby aws-sdk amazon-simpledb

使用AWS SDK for Ruby v1.0时,检查simpleDB域是否存在很简单:

def domain_exists?(domain_name)
  sdb =  AWS::SimpleDB.new
  domain = sdb.domains[domain_name]
  domain.exists?
end

但是,使用AWS SDK for Ruby的v2.0已经不再可能了。如何使用v2.0检查simpleDB域是否存在?

1 个答案:

答案 0 :(得分:0)

这有两种方法可以做到这一点。

  1. 使用domain_metadata并捕获异常。

    def domain_exists?(domain_name)
      sdb = Aws::SimpleDB::Client.new
      sdb.domain_metadata(domain_name: domain_name)
      return true
    rescue Aws::SimpleDB::Errors::NoSuchDomain 
      return false
    end
    
  2. 重新打开Aws::SimpleDB::Client类并添加使用domain_exists?的递归方法list_domains

    class Aws::SimpleDB::Client
      def domain_exists?(domain_name, limit = 100, next_token=nil)
        resp = list_domains(next_token: next_token, max_number_of_domains: limit)
        domain_exists = resp.domain_names.include?(domain_name)
        return domain_exists if domain_exists # found the domain
        return domain_exists if resp.next_token.nil? # no more domains to search
        domain_exists?(domain_name, limit, resp.next_token) # more domains to search
      end
    end
    

    然后变得非常简单:

    def domain_exists?(domain_name, limit = 100)
       sdb = Aws::SimpleDB::Client.new
       sdb.domain_exists?(domain_name, limit)
    end