我写了一个简单的并发调度器,但它似乎在高并发时有性能问题。
这是代码(调度器+并发速率限制器测试):
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
"sync"
"time"
"github.com/gomodule/redigo/redis"
)
// a scheduler is composed by load function and process function
type Scheduler struct {
// query channel
reqChan chan interface{}
// max routine
maxRoutine int
// max routine
chanSize int
wg sync.WaitGroup
// query process function
process func(interface{})
}
func NewScheduler(maxRoutine int, chanSize int, process func(interface{})) *Scheduler {
s := &Scheduler{}
if maxRoutine == 0 {
s.maxRoutine = 10
} else {
s.maxRoutine = maxRoutine
}
if chanSize == 0 {
s.chanSize = 100
} else {
s.chanSize = chanSize
}
s.reqChan = make(chan interface{}, s.chanSize)
s.process = process
return s
}
func (s *Scheduler) Start() {
// start process
for i := 0; i < s.maxRoutine; i++ {
go s.processRequest()
}
}
func (s *Scheduler) processRequest() {
for {
select {
case req := <-s.reqChan:
s.process(req)
s.wg.Done()
}
}
}
func (s *Scheduler) Enqueue(req interface{}) {
select {
case s.reqChan <- req:
s.wg.Add(1)
}
}
func (s *Scheduler) Wait() {
s.wg.Wait()
}
const script = `
local required_permits = tonumber(ARGV[2]);
local next_free_micros = redis.call('hget',KEYS[1],'next_free_micros');
if(next_free_micros == false) then
next_free_micros = 0;
else
next_free_micros = tonumber(next_free_micros);
end;
local time = redis.call('time');
local now_micros = tonumber(time[1])*1000000 + tonumber(time[2]);
--[[
try aquire
--]]
if(ARGV[3] ~= nil) then
local micros_to_wait = next_free_micros - now_micros;
if(micros_to_wait > tonumber(ARGV[3])) then
return micros_to_wait;
end
end
local stored_permits = redis.call('hget',KEYS[1],'stored_permits');
if(stored_permits == false) then
stored_permits = 0;
else
stored_permits = tonumber(stored_permits);
end
local stable_interval_micros = 1000000/tonumber(ARGV[1]);
local max_stored_permits = tonumber(ARGV[1]);
if(now_micros > next_free_micros) then
local new_stored_permits = stored_permits + (now_micros - next_free_micros) / stable_interval_micros;
if(max_stored_permits < new_stored_permits) then
stored_permits = max_stored_permits;
else
stored_permits = new_stored_permits;
end
next_free_micros = now_micros;
end
local moment_available = next_free_micros;
local stored_permits_to_spend = 0;
if(stored_permits < required_permits) then
stored_permits_to_spend = stored_permits;
else
stored_permits_to_spend = required_permits;
end
local fresh_permits = required_permits - stored_permits_to_spend;
local wait_micros = fresh_permits * stable_interval_micros;
redis.replicate_commands();
redis.call('hset',KEYS[1],'stored_permits',stored_permits - stored_permits_to_spend);
redis.call('hset',KEYS[1],'next_free_micros',next_free_micros + wait_micros);
redis.call('expire',KEYS[1],10);
return moment_available - now_micros;
`
var (
rlScript *redis.Script
)
func init() {
rlScript = redis.NewScript(1, script)
}
func take(key string, qps, requires int, pool *redis.Pool) (int64, error) {
c := pool.Get()
defer c.Close()
var err error
if err := c.Err(); err != nil {
return 0, err
}
reply, err := rlScript.Do(c, key, qps, requires)
if err != nil {
return 0, err
}
return reply.(int64), nil
}
func NewRedisPool(address, password string) *redis.Pool {
pool := &redis.Pool{
MaxIdle: 50,
IdleTimeout: 240 * time.Second,
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
Dial: func() (redis.Conn, error) {
return dial("tcp", address, password)
},
}
return pool
}
func dial(network, address, password string) (redis.Conn, error) {
c, err := redis.Dial(network, address)
if err != nil {
return nil, err
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
return c, err
}
func main() {
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile `file`")
var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
test()
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
f.Close()
}
}
func test() {
pool := NewRedisPool("127.0.0.1:6379", "")
s1 := NewScheduler(10000, 1000000, func(r interface{}) {
take("xxx", 1000000, 1, pool)
})
s1.Start()
start := time.Now()
for i := 0; i < 100000; i++ {
s1.Enqueue(i)
}
fmt.Println(time.Since(start))
s1.Wait()
fmt.Println(time.Since(start))
}
问题是在 10000 个例程时,有时即使没有向 redis 发送命令(检查“redis-cli monitor”)程序也会卡住,我的系统最大打开文件数设置为 20000。
我做了分析,很多“syscall.Syscall”,有人可以提供任何建议吗?我的调度程序有问题吗?
最佳答案
从表面上看,我唯一有疑问的是递增 WaitGroup 的排序和工作排队:
func (s *Scheduler) Enqueue(req interface{}) {
select {
case s.reqChan <- req:
s.wg.Add(1)
}
}
我认为上述内容在如此大的工作量下不会在实践中造成太大问题,但我认为这可能是一种合乎逻辑的竞争条件。在较低的并发级别和较小的工作量下,它可能会将消息排入队列,然后切换到开始处理该消息的 goroutine,然后是 WaitGroup 中的工作。
接下来你确定 process 方法是线程安全的吗??我假设基于 redis go 文档,使用 go run -race 运行是否有任何输出?
在某些时候,性能下降是完全合理和预期的。我建议开始性能测试,看看延迟和吞吐量从哪里开始下降:
可能是 10、100、500、1000、2500、5000、10000 或任何有意义的池。 IMO 看起来有 3 个重要变量需要调整:
MaxActive跳出来的最大的东西就是看起来像redis.Pool is configured to allow an unbounded number of connections :
pool := &redis.Pool{
MaxIdle: 50,
IdleTimeout: 240 * time.Second,
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
Dial: func() (redis.Conn, error) {
return dial("tcp", address, password)
},
}
// Maximum number of connections allocated by the pool at a given time. // When zero, there is no limit on the number of connections in the pool. MaxActive int
我个人会尝试了解相对于您的工作线程池大小,性能在何时何地开始下降。这可能会让您更容易理解您的程序受什么约束。
关于golang + redis 并发调度器性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55768699/
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search
由于fast-stemmer的问题,我很难安装我想要的任何rubygem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。
首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有, 也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加
如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是: