Skip to content

Instantly share code, notes, and snippets.

@laser
Created February 12, 2014 17:46
Show Gist options
  • Save laser/8960754 to your computer and use it in GitHub Desktop.
Save laser/8960754 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'barrister'
require 'pry'
require 'redis'
require 'erb'
# App
require './models.rb'
require './service.rb'
# establish connection to main db
db_config = YAML.load(ERB.new(File.read('../../config/database.yml')).result)
RACK_ENV ||= ENV['RACK_ENV'] || 'development'
ActiveRecord::Base.establish_connection(db_config[RACK_ENV])
# establish connection to Redis
redis_config = YAML.load(ERB.new(File.read('../../config/redis.yml')).result)['user_service']
client = Redis.connect url: ENV['OPENREDIS_URL'] || redis_config['database_url']
# initialize service
contract = Barrister::contract_from_file('./user_service.json')
server = Barrister::Server.new(contract)
server.add_handler('UserService', UserService.new)
while true
# pop last element off our list in a blocking fashion
channel, request = client.brpop(redis_config['list_name'])
parsed = JSON.parse request
# reverse the message we were sent
response = {
'message' => server.handle(parsed['message'])
}
# 'respond' by inserting our reply at the head of a 'reply'-list
client.lpush(parsed['reply_to'], JSON.generate(response))
end
require './service.rb'
container = Barrister::RedisContainer.new(ENV['REDIS_URL'], './user_service.json', UserService)
container.run
require 'barrister'
require 'redis'
module Barrister
class RedisContainer
def initialize(redis_url, json_path, service_klass, interface_name=nil)
# establish connection to Redis
@client = Redis.connect url: ENV['OPENREDIS_URL']
# communication channel for this container
@list_name = service_klass.to_s
# initialize service
contract = Barrister::contract_from_file(json_path)
@server = Barrister::Server.new(contract)
@server.add_handler(interface_name || service_klass.to_s, service_klass.new)
end
def run
while true
# pop last element off our list in a blocking fashion
channel, request = client.brpop(@list_name)
parsed = JSON.parse request
# reverse the message we were sent
response = {
'message' => server.handle(parsed['message'])
}
# 'respond' by inserting our reply at the head of a 'reply'-list
client.lpush(parsed['reply_to'], JSON.generate(response))
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment