在EventMachine中建立Redis连接似乎有几种选择,我很难理解它们之间的核心区别。
我的目标是在歌利亚中实现Redis
我现在建立连接的方式是通过em-synchrony。
require 'em-synchrony'
require 'em-synchrony/em-redis'
config['redis'] = EventMachine::Synchrony::ConnectionPool.new(:size => 20) do
EventMachine::Protocols::Redis.connect(:host => 'localhost', :port => 6379)
end 与使用类似于em-hiredis的东西相比,上面的区别是什么?
如果我使用Redis作为集合和基本键:值存储,那么em-redis是我的场景的最佳解决方案吗?
发布于 2011-12-06 10:52:02
effectively所做的是修补em-redis宝石,允许将其与纤维一起使用,从而有效地使其在goliath中运行。
下面是一个使用Goliath + Redis的项目,它可以指导您如何完成所有这些工作:https://github.com/igrigorik/mneme
例如,使用em-hiredis,goliath所做的是将请求封装在纤维中,因此测试方法如下:
require 'rubygems'
require 'bundler/setup'
require 'em-hiredis'
require 'em-synchrony'
EM::run do
Fiber.new do
## this is what you can use in goliath
redis = EM::Hiredis.connect
p EM::Synchrony.sync redis.keys('*')
## end of goliath block
end.resume
end我用的Gemfile:
source :rubygems
gem 'em-hiredis'
gem 'em-synchrony'如果您运行此示例,您将得到在屏幕上打印的redis数据库中定义的键列表。如果没有EM::Synchrony.sync调用,您将得到一个可推迟的,但是在这里,光纤被挂起,直到调用返回,然后得到结果。
发布于 2012-05-18 03:55:19
我们在歌利亚非常成功地利用了他们。下面是我们如何编写发布代码的示例:
配置/示例_api.rb
# These give us direct access to the redis connection from within the API
config['redisUri'] = 'redis://localhost:6379/0'
config['redisPub'] ||= EM::Hiredis.connect('')example_api.rb
class ExampleApi < Goliath::API
use Goliath::Rack::Params # parse & merge query and body parameters
use Goliath::Rack::Formatters::JSON # JSON output formatter
use Goliath::Rack::Render # auto-negotiate response format
def response(env)
env.logger.debug "\n\n\nENV: #{env['PATH_INFO']}"
env.logger.debug "REQUEST: Received"
env.logger.debug "POST Action received: #{env.params} "
#processing of requests from browser goes here
resp =
case env.params["action"]
when 'SOME_ACTION' then process_action(env)
when 'ANOTHER_ACTION' then process_another_action(env)
else
# skip
end
env.logger.debug "REQUEST: About to respond with: #{resp}"
[200, {'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => "*"}, resp]
end
# process an action
def process_action(env)
# extract message data
data = Hash.new
data["user_id"], data["object_id"] = env.params['user_id'], env.params['object_id']
publishData = { "action" => 'SOME_ACTION_RECEIVED',
"data" => data }
redisPub.publish("Channel_1", Yajl::Encoder.encode(publishData))
end
end
return data
end
# process anothr action
def process_another_action(env)
# extract message data
data = Hash.new
data["user_id"], data["widget_id"] = env.params['user_id'], env.params['widget_id']
publishData = { "action" => 'SOME_OTHER_ACTION_RECEIVED',
"data" => data }
redisPub.publish("Channel_1", Yajl::Encoder.encode(publishData))
end
end
return data
end
end处理订阅是留给读者的练习。
https://stackoverflow.com/questions/8088314
复制相似问题