mongrel_rails - 以编程方式报告它正在运行的端口

时间:2015-05-13 09:12:06

标签: ruby-on-rails mongrel mongrel-cluster

在我的本地机器上,我用mongrel运行rails。我有一些在启动时运行的东西,通过config / initializers中的文件,它使用puts来告诉我它使用了哪个数据库,用于发送电子邮件的内容以及其他一些位信息。

当我在端口3000,3001和3002上运行mongrel集群时,我只想在端口3000上为mongrel执行此报告。因此,我需要将其包装在if块中测试当前运行的mongrel正在使用哪个端口。谁能告诉我如何在我的代码中得到这个?

3 个答案:

答案 0 :(得分:2)

在初始化程序中,

public class Owner extends Person {

    static {
        KryoDowncastCloneUtil.instance().register(Person.class, Owner.class);
    }

    // ...

    public static Owner fromPerson(Person person) {
        return KryoDowncastCloneUtil.instance().copyAndDowncast(person, Owner.class);
    }
}

可以报告您的端口。

答案 1 :(得分:1)

好的,我正在回答我自己的问题,因为我只是在设定赏金后想出来了!

我可以使用Process.pid获取当前正在运行的进程的 pid 。然后我可以ps afx | grep mongrel给我一个像这样的结果

 pid                                                                                 port
  |                                                                                    |
  V                                                                                    V
10761 pts/1    S      0:20  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3000
10762 pts/1    S      0:18  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3001
10763 pts/1    S+     0:23  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3002

然后我可以grep为pid,并从匹配行中读取端口号,看看它是否为3000。

所以,我的代码是

if `ps afx | grep mongrel_rails`.split("\n").detect{|line| line =~ /^#{Process.pid}.+\-p\s3000/}
  #this is a mongrel running on port 3000 - do the extra stuff
  ....
end
顺便说一句,如果有人能告诉我如何直接获取正在运行的杂种的端口,而不通过ps afxProcess.pid,我仍会给你赏金:)

答案 2 :(得分:1)

Does this work in 2.2.2?

class SomeController < ApplicationController

  def index
        @port = request.port
  end
end
相关问题