Examples

Pub/Sub

This example shows how to to Publish/Subscribe with TurboRedis.

 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
local turboredis = require("turboredis")
local yield = coroutine.yield
local ioloop = turbo.ioloop.instance()

ioloop:add_callback(function () 
	-- Create a normal redis connection for publishing
	local pubcon = turboredis.Connection:new({host="127.0.0.1", port=6379})	
	
	-- Create a PubSub Connection for subscribing
	-- This has the subscriber commands
	local subcon = turboredis.PubSubConnection:new({host="127.0.0.1", port=6379})

	-- Connect both
	yield(pubcon:connect())
	yield(subcon:connect())

	-- Subscribe to the channel 'hello.msgs'
	yield(subcon:subscribe("hello.msgs"))

	-- Wait for messages.
	-- After start() is called, no commands other than
	-- subscribe/unsubscribe commands can be used.
	subcon:start(function (msg)
		print("NEW MESSAGE:")
		print("  Message type: " .. msg.msgtype)	
		print("  Channel: " .. msg.channel)
		print("  Data: " .. msg.data)
		print("--")

		-- If the message is 'exit', close the IOLoop
		if msg.data == "exit" then
			ioloop:close()
		end
	end)

	-- Publish messages
	yield(pubcon:publish("hello.msgs", "Hello "))
	
	ioloop:add_timeout(turbo.util.gettimemonotonic() + 1000, function () 
		yield(pubcon:publish("hello.msgs", "World!!"))
	end)

	ioloop:add_timeout(turbo.util.gettimemonotonic() + 2000, function () 
		yield(pubcon:publish("hello.msgs", "exit"))
	end)
end)

ioloop:start()

GitHub API Caching

This example is a simple app that retrieves the repository list of a GitHub user and caches the responses from the GitHub API in Redis for a limited time.

 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
TURBO_SSL = true -- Enable SSL since we are querying a https:// url.
local turbo = require("turbo")
local turboredis = require("turboredis")
local yield = coroutine.yield
local GITHUB_URL = "https://api.github.com/users/%s/repos"

-- Create a new connection to Redis
local redis = turboredis.Connection:new({host="127.0.0.1", port=6379})

local GitHubRepoListHandler = class("GitHubRepoListHandler",
                                    turbo.web.RequestHandler)

function GitHubRepoListHandler:get(username)
    -- Set the async option to force Turbo to not finish up
    -- the request before we say so.
    self:set_async(true)

    local cache_key = "github_repolist_" + username

    -- Try to retrieve the response from cache.
    local r = yield(redis:get(cache_key))

    -- If the repo list was found in cache, write it to the client
    -- and return
    if r then
        local repolist = turbo.escape.json_decode(r)
        self:write_repolist(repolist)
        self:write("<br><b>cach hit<b>")
        -- Get the remaining time-to-live for the Redis key
        redis:ttl(cache_key, function (ttl)
            self:write(string.format("<br><b>ttl: %d", ttl)) 
            self:finish()
        end)
        return
    end

    -- If the repo list wasn't cached, fetch it from GitHub
    local res = yield(turbo.async.HTTPClient():fetch(
        string.format(GITHUB_URL, username), {verify=true}))

    local status_code = res.headers:get_status_code()
    if status_code ~= 200 then
        if status_code == 404 then -- Not found
            self:write(string.format("User '%s' not found", username))
            return
        else -- Other error
            error(turbo.web.HTTPError:new(500, res.error.message))
        end
    end

    local repolist = turbo.escape.json_decode(res.body)
    self:write_repolist(repolist)
    self:write("<br><b>cache miss<b>")
    self:finish()

    -- Set the key github_repolist_<USERNAME> to the response
    -- body string and set it to expire in 10 seconds
    r = yield(redis:setex(cache_key, 10, res.body))
    if not r then
        -- We should never get here.
        turbo.log.warning("Could not cache response body from github")
    end
end

-- Writes a repo list to client as an HTML unordered list with the repo
-- name and what github consideres the primary language used in the repo.
function GitHubRepoListHandler:write_repolist(repolist)
    self:write("<h1>Repositories</h1><ul>")
    for i, repo in ipairs(repolist) do
        self:write(string.format([[<li><a href="%s">%s(%s)</a></li>]],
            repo.url, repo.name, repo.language))
    end
    self:write("</ul>")
end

local app = turbo.web.Application({
    {"^/(.-)$", GitHubRepoListHandler}
}):listen(8888)

turbo.ioloop.instance():add_callback(function ()
    yield(redis:connect())
end)
turbo.ioloop.instance():start()

turbo.ioloop.instance():start()

Command Line Redis Client

This example implments a super-simple command line client for doing Redis commands.

 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
--
-- TurboRedis run() example.
--
-- Shows how to use turboredis.Connection:run() to make a very simple command line
-- redis client.
--
--

local turbo = require("turbo")
local turboredis = require("turboredis")
local yield = coroutine.yield

local USAGE = "Usage: luajit rediscmd.lua COMMAND [SUBCOMMAND] [ARGUMENTS ...]"

turbo.ioloop.instance():add_callback(function () 
	local redis = turboredis.Connection:new({host="127.0.0.1", port=6379})	
	local r = yield(redis:connect())
	if not r then
		print("Could not connect to Redis")
		return
	end

    -- No command, print usage.
    if #arg == 0 then
        print(USAGE)
        turbo.ioloop.instance():close()
    end
	
    -- Copy relevant arguments into cmd.
    local cmd = {}
    for i=1,#arg do
        cmd[#cmd+1] = arg[i]
    end

    -- Run the command and print the result.
    redis:run(cmd, function (r, x)
        print(r, x)
        turbo.ioloop.instance():close()
    end)

end)
turbo.ioloop.instance():start()

TurboRedis

Navigation

Fork me on GitHub