我使用 redis 作为读取缓存。我创建了一个初始化程序
配置/初始化程序/redis.rb
$redis = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
每当创建新工作人员时,我都会在 unicorn.rb 中使用此全局变量来创建新连接。
before_fork do |server, worker|
# clear redis connection
$redis.quit unless $redis.blank?
end
# Give each child process its own Redis connection
after_fork do |server, worker|
$redis = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
end
每当我需要访问我的 Redis 服务器时,我也会使用这个全局变量。但我不习惯使用这个全局变量。还有比使用全局变量更好的选择吗?
有Redis.current
,您可以用它来存储您唯一的Redis
实例。
所以不要使用$redis
,您可以按如下方式分配实例:
Redis.current = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
Redis.current
was 2010年引入redis-rb https://github.com/redis/redis-rb/commit/23ed5974e96e89f4ef691139a9380a9d08e9cec6作为获取 Redis 连接的标准方法,所以我很惊讶没有其他答案提到它。
Update:从 4.6.0 版本开始Redis.current
已被弃用 https://github.com/redis/redis-rb/commit/9745e22db65ac294be51ed393b584c0f8b72ae98。作者指出,典型的多线程应用程序会在共享 Redis 客户端周围发现大量锁定。他们建议定义一个自己的地方来获取 Redis 客户端,但也建议使用连接池。
因此,接受的答案是实现类似效果的最简单的解决方案Redis.current
,但在多线程环境中可能无法实现最佳性能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)