lua 入门教程
https://www.runoob.com/lua/lua-tutorial.html
openResty官网
由于Cassandra官方并没有提供lua的官方驱动,所以本文使用开源项目lua-cassandra 来连接cassandra,关于lua-cassandra的资料如下:
git: https://github.com/thibaultcha/lua-cassandra
wiki: https://thibaultcha.github.io/lua-cassandra/
注意:
lua连接cassandra 的程序是需要运行在openResty环境中的,所以请提前搭建好openResty环境以及安装好lua-cassandra 驱动库
lua-cassandra 分为两个单机版和集群版,由于单纯使用单机版没有意义,本文以集群版驱动为例使用
引入驱动库以及连接cassandra集群
|
1
2
3
4
5
6
7
8
9
10
11
12
|
01 --引入驱动库 02 local Cluster = require "resty.cassandra.cluster" 03 --初始化集群信息并通过连接点连接集群 04 local cluster, err = Cluster.new {
05 shm = "cassandra", -- defined by the lua_shared_dict directive
06 contact_points = {"127.0.0.1"},
07 keyspace = "keyspace_name" 08 } 09 if not cluster then
10 ngx.log(ngx.ERR, "could not create cluster: ", err)
11 return ngx.exit(500)
12 end |
创建keyspace和table
|
1
2
3
4
5
6
7
|
1 --注意keyspace和table 参数处需要使用转义符,不然会报错 2 local create_keyspace, err = cluster:execute "CREATE KEYSPACE ks_test WITH replication = {\'class\':\'SimpleStrategy\', \'replication_factor\' : 1};" 3 4 local use_keyspace, err = cluster:execute "use kb_test;" 5 6 7 local create_table, err = cluster:execute "CREATE TABLE tb_test (k int,p int,s int static,v int,PRIMARY KEY (k, p));"
|
select 查询
|
1
2
3
4
5
6
7
|
1 local rows, err = cluster:execute "SELECT * FROM tb_test" 2 if not rows then
3 ngx.log(ngx.ERR, "could not retrieve users: ", err)
4 return ngx.exit(500)
5 end 6 7 ngx.say("users: ", #rows)
|
batch查询
|
1
2
3
4
5
6
7
8
9
10
11
12
|
01 local res, err = cluster:batch({ 02 {"INSERT INTO a(id, age) VALUES(?, 7)", {123}},
03 {"UPDATE a SET age = 2 WHERE id = ?", {3}},
04 {"UPDATE a SET age = 3 WHERE id = ?", {4}}
05 }, { 06 logged = false 07 }) 08 09 if not res then
10 ngx.log(ngx.ERR, "could not execute batch: ", err)
11 ngx.exit(500)
12 end |
drop表操作
|
1
2
3
4
5
6
7
|
1 local use_keyspace, err = cluster:execute "use ks_test;" 2 3 local del_test ,err = cluster:execute "drop table tb_test;" 4 if not del_test then
5 ngx.log(ngx.ERR, "could not execute drop: ", err)
6 ngx.exit(500)
7 end |
allow filter 查询
|
1
2
3
4
5
6
7
8
9
10
|
01 local use_keyspace, err = cluster:execute "use ks_test;" 02 03 local allowfiltering ,err = cluster:execute "SELECT * FROM tb_test where age=7 allow filtering;" 04 if not allowfiltering then
05 ngx.log(ngx.ERR, "could not execute drop: ", err)
06 ngx.exit(500)
07 end 08 for idx, var in pairs(allowfiltering) do 09 ngx.say(string.format("列名,数据:%s:%s", idx, var))
10 end |
写入数据
|
1
2
3
4
5
6
7
|
1 local use_keyspace, err = cluster:execute "use ks_test;" 2 3 local usettl ,err = cluster:execute "INSERT INTO tb_test(id, age) VALUES(666, 7) using ttl 20;" 4 if not usettl then
5 ngx.log(ngx.ERR, "could not execute drop: ", err)
6 ngx.exit(500)
7 end |

来支持了
Campus Hero
2020-5-8 12:35