如何在rails中配置dynamodb?

时间:2017-08-08 05:34:33

标签: ruby-on-rails ruby amazon-web-services amazon-dynamodb

在rails 5中,我需要配置dynamodb功能。我已经推荐了一些博客,并尝试实施它。首先在localhost中它运行没有任何问题,但当我移动到其他新系统或服务器时,它显示错误,如,

/home/NICHEPRO/shruthir/.rvm/gems/ruby-2.4.0/gems/aws-sdk-core-2.10.19/lib/aws-sdk-core/plugins/regional_endpoint.rb:34:in `after_initialize': missing region; use :region option or export region name to ENV['AWS_REGION'] (Aws::Errors::MissingRegionError)
from /home/NICHEPRO/shruthir/.rvm/gems/ruby-2.4.0/gems/aws-sdk-core-2.10.19/lib/seahorse/client/base.rb:84:in `block in after_initialize'

AWS gem是,

aws-sdk (2.10.19)
aws-sdk-core (2.10.19)
aws-sdk-resources (2.10.19)

参考:

https://assist-software.net/snippets/how-save-data-amazon-dynamodb-using-ruby-on-rails

此外,我试图通过引用其他博客来解决这个问题,但我也会得到以下错误,

Failed to open TCP connection to localhost:8080 (Connection refused - connect(2) for "localhost" port 8080)

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

希望你使用的是Dynamoid gem。在app/config/initializer中添加新的配置文件并添加以下代码。

Dynamoid.configure do |config|
  config.adapter = 'aws_sdk_v2' # This adapter establishes a connection to the DynamoDB servers using Amazon's own AWS gem.
  config.access_key = (ENV['AWS_ACCESS_KEY_ID'] || APP_CONFIG[:aws_access_key_id])
  config.secret_key = (ENV['AWS_SECRET_ACCESS_KEY'] || APP_CONFIG[:aws_secret_access_key])
  config.region = (ENV['AWS_REGION'] || 'us-east-1')
  config.namespace = nil # To namespace tables created by Dynamoid from other tables you might have. Set to nil to avoid namespacing.
  config.warn_on_scan = true # Output a warning to the logger when you perform a scan rather than a query on a table.
  config.read_capacity = 100 # Read capacity for your tables
  config.write_capacity = 200 # Write capacity for your tables
  config.endpoint = (ENV['DYNAMO_ENDPOINT'] || APP_CONFIG[:dynamo_endpoint]) # [Optional]. If provided, it communicates with the DB listening at the endpoint. This is useful for testing with [Amazon Local DB] (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html).
end

确保更新ENV变量。或者,如果您直接连接到AWS而不是Dynamoid gem,请关注...

def client
  @client ||= Aws::DynamoDB::Client.new(
    access_key_id: (ENV['AWS_ACCESS_KEY_ID'] || APP_CONFIG[:aws_access_key_id]),
    secret_access_key: (ENV['AWS_SECRET_ACCESS_KEY'] || APP_CONFIG[:aws_secret_access_key]),
    region: (ENV['AWS_REGION'] || 'us-east-1'),
    endpoint: (ENV['DYNAMO_ENDPOINT'] || APP_CONFIG[:dynamo_endpoint])
  )
end

并执行此类查询

client.query(
    table_name: table_name,
    select: 'COUNT',
    expression_attribute_values: {
      ':v1' => index
    },
    key_condition_expression: 'user_id = :v1'
  ).count

了解更多信息http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/DynamoDB.html