简体   繁体   English

如何将本地项目库引入 ruby​​ aws lambda 函数?

[英]How to require local project library into ruby aws lambda function?

I have a ruby lambda function and now it needs database connection using mysql2.我有一个 ruby​​ lambda 函数,现在它需要使用 mysql2 进行数据库连接。

Now, using lambda function console editor I uploaded my zip file with my library inside vendor/bundle.现在,使用 lambda 函数控制台编辑器,我将我的 zip 文件和我的库上传到供应商/捆绑包中。

I installed the library in my local using below command我使用以下命令在本地安装了库

bundle install --path vendor/bundle捆绑安装 --path 供应商/捆绑

to install mysql2 ~> 0.5.2 from the Gemfile.从 Gemfile 安装 mysql2 ~> 0.5.2。

Now, I wrote below code to get data from db现在,我写了下面的代码来从数据库中获取数据

require 'json'
load_paths = Dir.pwd + "/vendor/bundle/ruby/2.5.0/gems/**/lib"
$LOAD_PATH.unshift(*load_paths)
require 'mysql2'
def lambda_handler()
  @db_host  = "host"
  @db_user  = "user"
  @db_pass  = "pass"
  @db_name = "db"

  client = Mysql2::Client.new(:host => @db_host, :username => @db_user, :password => @db_pass, :database => @db_name)
  @cdr_result = client.query("SELECT count(*) from names")
  puts @cdr_result
  { statusCode: 200, body: JSON.generate('Hello from Lambda!') }
end
lambda_handler

but throwing this error in aws lambda但是在 aws lambda 中抛出这个错误

Response:
{
  "errorMessage": "cannot load such file -- mysql2",
  "errorType": "Init<LoadError>",
  "stackTrace": [
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/task/replaceFile.rb:4:in `<top (required)>'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'"
  ]
}

Is there any way that I can require the local directory mysql2 gem into my script file having my gems inside vendor/bundle and use these libraries in my ruby script, which is in aws lambda deployment package.有什么方法可以要求将本地目录 mysql2 gem 放入我的脚本文件中,其中我的 gem 位于供应商/捆绑包中,并在我的 ruby​​ 脚本中使用这些库,该脚本位于 aws lambda 部署包中。

Apparently other answers do not work for Ruby 2.7.0.显然其他答案不适用于 Ruby 2.7.0。

It worked for me with它对我有用

$LOAD_PATH.unshift *Dir['/var/task/app_name/vendor/ruby/2.7.0/gems/**/lib']

Be sure to change app_name to the name of your lambda function.请务必将app_name更改为 lambda 函数的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM