部署 Thin 的疑似内存泄漏

lithium4010 · November 30, 2016 · Last by lithium4010 replied at December 13, 2016 · 2544 hits

发现 thin 开多线程模式以后,一个请求要吃掉 30M 的内存而且不回收。 关掉多线程模式以后,内存占用相对稳定。 有没有人知道怎么回事?

调查了一下,这个 thin --threaded 有个线程池,默认大小是 20,我猜想这样程序刚起来的时候,收到一个请求就会起一个新的线程,直到线程池满。

下面是一个简单的例子

# uname -a
Linux ****** 3.10.0-229.11.1.el7.x86_64 #1 SMP Thu Aug 6 01:06:18 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
# Gemfile
source 'https://gems.ruby-china.org'

gem 'thin'
gem 'oj'
# Gemfile.lock

GEM
  remote: https://gems.ruby-china.org/
  specs:
    daemons (1.2.4)
    eventmachine (1.2.1)
    oj (2.18.0)
    rack (2.0.1)
    thin (1.7.0)
      daemons (~> 1.0, >= 1.0.9)
      eventmachine (~> 1.0, >= 1.0.4)
      rack (>= 1, < 3)

PLATFORMS
  ruby

DEPENDENCIES
  oj
  thin

BUNDLED WITH
   1.13.6
# config.ru
require 'rack'
require 'rack/server'
require 'oj'

class TestThin
  def self.call(env)
    json = Oj.dump((0...20000).to_a.map { |i| {name: "name_#{i}", code: i.to_s} })
    [200, {}, json]
  end
end

run TestThin

手动 20 次 curl localhost:3555

同时使用

while true; do TEXT=$(ps -ef | grep 3555 | grep ruby | awk '{print $2}' | xargs ps -o rss= -p); sleep 1; echo "$TEXT"; done

查看内存占用

# bundle exec thin -R config.ru -p 3555 start

20720
24896
24896
24896
24896
24896
24896
24896
31384
31384
37984
39476
40268
40268
41060
41852
42380
43172
43964
44756
44756
45548
46076
46868
47660
47924
47924
47924

# bundle exec thin -R config.ru -p 3555 start --threaded

24924
31944
39944
39944
45956
51968
57980
57980
59612
65624
65952
65952
66280
72292
78304
78304
84316
84644
88072
90656
90984
96996
100424
103008
109020
115032
119516
121044
121044
121044
121044
126056
126556
126556
126556
126556

用 Puma 啊,Thin 现在没维护了吧

#1 楼 @huacnlee 之前试着换到 puma,然而踩到了一个 send_file 没法用的坑。。。

#1 楼 @huacnlee 今年 Owning Rails 的课程价格都便宜了不少...感觉那哥们最近不太景气啊...

什么类型的请求

#4 楼 @realwol GET 一个大 json, 好几兆

#3 楼 @jasl 话说那门课怎么样啊?值得学习么?

#5 楼 @lithium4010 我觉得多数可能性还是在你的代码里吧,如果有 db 操作,看看是不是 table 全属性加载了,或者关联表也加载了什么的。

#7 楼 @realwol 哦,不是的,这个现象是如果我不用多线程模式,就不会有这么夸张的内存增长。

说了这么久,代码呢?

新的代码块样式挺好看的

You need to Sign in before reply, if you don't have an account, please Sign up first.