-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRedisMysql.rb
66 lines (51 loc) · 1.43 KB
/
RedisMysql.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env ruby
#
# # Example Class Usage
# rm = RedisMysql.new
# results = rm.query 'user_page_views:1', 10
#
# # debug
# puts results
#
require 'rubygems'
require 'redis'
require 'json'
require 'mysql2'
class RedisMysql
def initialize
@redis = Redis.new
@mysql = Mysql2::Client.new(:host => 'localhost', :username => 'root', :password => 'PASSWORD', :database => 'redisgearman')
@redis_results = []
end
def query(key, limit)
@redis_results = query_redis key,limit
return @redis_results if @redis_results.size >= limit
@mysql_results = query_mysql key, (limit-@redis_results.size)
@redis_results.concat @mysql_results
end
def query_redis(key, limit)
results = @redis.lrange key, 0, limit
return [] if results.nil?
results.collect {|r| JSON.parse r}
end
def query_mysql(key, limit)
# parse args
parts = key.split ':'
mysql_table = parts[0]
user_id = parts[1]
# get last timestamp from redis results
last_timestamp = @redis_results.last['timestamp'] unless @redis_results.empty?
where = []
where << "user_id = '#{@mysql.escape user_id}'"
where << "timestamp < '#{@mysql.escape last_timestamp}'" unless last_timestamp.nil?
sql = "
select *
from user_page_views
where #{where.join ' and '}
order by id desc
limit #{limit}"
results = @mysql.query sql
return [] if results.nil?
results.collect {|r| r}
end
end