intro.lua
local cassandra = require "cassandra"
local client = assert(cassandra.new {
host = "127.0.0.1",
keyspace = "my_keyspace"
})
client:settimeout(1000)
assert(client:connect())
local res = assert(client:execute [[
CREATE TABLE users(
id uuid PRIMARY KEY,
name varchar,
age int
)
]])
print(res.type)
res = assert(client:execute("INSERT INTO users(id, name, age) VALUES(?, ?, ?)", {
cassandra.uuid("1144bada-852c-11e3-89fb-e0b9a54a6d11"),
"John O Reilly",
42
}))
print(res.type)
local rows = assert(client:execute("SELECT * FROM users WHERE age = ?", {
age = 42 }, {
named = true }))
print(rows.type) print(#rows) print(rows[1].name)
client:close()
local cassandra = require "cassandra"
local Cluster = require "resty.cassandra.cluster"
local cluster
local _M = {}
function _M.init_cluster(...)
cluster = assert(Cluster.new(...))
assert(cluster:refresh())
end
function _M.execute(...)
return cluster:execute(...)
end
return _M
http {
lua_shared_dict cassandra 1m; # shm storing cluster information
lua_code_cache on; # ensure the upvalue is preserved beyond a single request
init_by_lua_block {
local my_module = require "my_module"
my_module.init_cluster {
shm = "cassandra", contact_points = {"127.0.0.1", "127.0.0.2"},
keyspace = "my_keyspace"
}
}
server {
location / {
content_by_lua_block {
local my_module = require "my_module"
local rows, err = my_module.execute("SELECT * FROM users WHERE id = ? AND name = ?", {
cassandra.uuid("1144bada-852c-11e3-89fb-e0b9a54a6d11"),
"John O Reilly"
})
if not rows then
ngx.log(ngx.ERR, "could not retrieve users: ", err)
ngx.exit(500)
end
for i, row in ipairs(rows) do
ngx.say(i, ": ", rows[i].name) end
}
}
}
}