Unicorn简介
unicorn是Rake应用程序设计的HTTP server(Ruby应用级服务器)
Unicorn安装
$ gem install unicorn
在 Gemfile
中加入
# Use Unicorn as the app server
gem 'unicorn'
Unicorn配置
在你的 Rails 项目跟目录中新建 unicorn.conf.rb
文件将以下代码复制进去
# 配置项目在该计算机中的绝对路径
module YOU_APP_NAME
class << self
def root
File.expand_path("..", __FILE__)
end
end
end
# 工作进程数量
# worker_processes 2 表示同一时间只能处理两个请求
# 具自身应用情况而定
worker_processes 2
# 项目工作路径
# 这里一般为你应用在该机器上的绝对路径
# 用上面的 module 即可
working_directory YOU_APP_NAME.root
# 监听 Unix 本地 socket 或 TCP 端口
# 下面的路径可随意设置,他会自动生成一个 .sock 文件
# 但是一般放在项目路径下,或者
# "/tmp/YOU_APP_NAME.unicorn.sock"
listen "#{YOU_APP_NAME.root}/tmp/YOU_APP_NAME.unicorn.sock", :backlog => 64
# 开启tcp 端口,可不使用 apache 或 nginx 做代理,直接本地:http://localhost:port
# 8080为你需要开启的端口,根据自身应用情况而定
# 这里也可以写成
# listen "XX.XX.XX.XX:8080" IP加端口的形式(但是unicorn默认会带上本机IP)
# 一定要注意写成IP加端口的形式话一定要加双引号!只写端口可不加
listen 8080, :tcp_nopush => true
# request 超时时间,超过此时间则自动将此请求杀掉,单位为秒(默认为 60s)
timeout 90
# pid 文件里面放入的是该 unicorn 进程ID
# 下面的路径可随意设置,他会自动生成一个 .pid 文件
# 但是一般放在项目路径下,或者
# "/tmp/pids/unicorn.pid"
# 为了在后期关闭或者重启该HTTP server 提供方便
# 在下面我将会把方法贴出来
pid "#{YOU_APP_NAME.root}/tmp/pids/unicorn.pid"
# unicorn的错误日志和输出日志
# 一般放在你项目下log文件夹中
stderr_path "#{YOU_APP_NAME.root}/log/unicorn.stderr.log"
stdout_path "#{YOU_APP_NAME.root}/log/unicorn.stdout.log"
# 用于节省内存
preload_app true
# 处理内存分配和资源共享
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
end
# 实现 unicorn 的无缝重启
before_fork do |server, worker|
old_pid = "#{Exchange2.root}/tmp/pids/unicorn.pid.oldbin"
if File.exists?(old_pid) && server.pid != old_pid
begin
Process.kill("QUIT", File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
puts "Send 'QUIT' signal to unicorn error!"
end
end
end
Unicorn启动
非 Rails Rack
应用程序
$ unicorn
Rails 应用程序
$ unicorn_rails
参数说明
-D
:以Deamon 形式启动(在后台运行)-c
:设定配置文件路径-E
:设定生产环境或开发环境,如-E production
或者-E development
例
$ bundle exec unicorn_rails -D -c /YOU_APP_NAME/unicorn.conf.rb -E production
Unicorn启动、关闭和重启
为了方便管理人员后期维护可以在 项目的根目录 创建三个ruby文件来对项目进行启动、关闭和重启
start.unicorn.rb
`bundle exec unicorn_rails -D -c unicorn.conf.rb -E development`
# 或者 production
stop.unicorn.rb
# 读取 unicorn.pid 中的 unicorn 进程ID
pid = File.open("tmp/pids/unicorn.pid").readlines.join.strip
# 杀掉此进程
`kill -9 #{pid}`
restart.unicorn.rb
# 读取 unicorn.pid 中的 unicorn 进程ID
pid = File.open("tmp/pids/unicorn.pid").readlines.join.strip
# 杀掉此进程
`kill -9 #{pid}`
`bundle exec unicorn_rails -D -c unicorn.conf.rb -E development`
# 或者 production
在后期启动、关闭和重启 unicorn 时,即可用
# 启动 unicorn
$ ruby start.unicorn.rb
# 关闭 unicorn
$ ruby stop.unicorn.rb
# 重启 unicorn
$ ruby restart.unicorn.rb
注意
该文档在rails
+ unicorn
时可行。如需 rails
+ Capistrano
+ unicorn
有一些小小的改动,这里不做说明。请注意