本人自行删除

lanjingyu · 2015年12月08日 · 最后由 jimrokliu 回复于 2015年12月11日 · 10261 次阅读

本人自行删除

全局变量,不用关闭

全局 + 1

# redis.rb
# redis conig
REDIS_CONFIG = YAML.load(File.open(Rails.root.join('config/redis.yml'))).symbolize_keys
default_config = REDIS_CONFIG[:default].symbolize_keys
redis_config = default_config.merge(REDIS_CONFIG[Rails.env.to_sym].symbolize_keys) if REDIS_CONFIG[Rails.env.to_sym]

$redis = Redis.new(redis_config)
# @see https://github.com/resque/redis-namespace
$namespaced_redis = Redis::Namespace.new(redis_config[:namespace], redis: $redis) if redis_config[:namespace]

# redis -> object
# @see https://github.com/nateware/redis-objects
# require 'connection_pool'
# Redis::Objects.redis = ConnectionPool.new(size: 5, timeout: 5) { $redis }

# To clear out the db before each test and development
begin
  $redis.flushdb if Rails.env == 'test'
  $redis.flushdb if Rails.env == 'development'
rescue Exception => e
  p '-' * 20
  p "Error trying with $redis.flushdb: #{e.message}"
  p 'You may need to start the redis-server with `sudo service redis-server start`'
  p 'If the redis-server is not installed, please `sudo apt-get install redis-server`.'
  p 'You are not using linux? See you.'
  p '-' * 20
  rails_pid = Process.pid # thanks @rubyist518
  cmd = "kill -SIGINT #{rails_pid}"
  `#{cmd}`
end
# config/redis.yml
default:
  host: localhost
  port: 6379
  driver: hiredis

development:
  db: 0
  namespace: app_development

test:
  db: 1
  namespace: app_test

production:
  db: 2
  host: 127.0.0.1
  namespace: app_production

@flowerwrong 配置文件中的rails_pid最好这样:

rails_pid = Process.pid

😄

全局变量感觉好 low,还是使用 singleton 吧

6 楼 已删除
7 楼 已删除
9 楼 已删除

#5 楼 @kikyous ruby 的 Singleton 的代码有问题,有锁。

#11 楼 @rei 有道理,学习了,那以后就用多数据库来区分项目,而不是 namespace 吧

13 楼 已删除

#13 楼 @lanjingyu 如果你用多线程去执行 Class.instance,你会发现有锁等待的情况。你打开 ruby singleton 的代码,你会看到里面用了锁。

15 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号