Redis 的 WebAPI(Genie)

这是一个满足设定规范的服务器端程序,并使用Genie进行实现。我们创建了一个Redis的WebAPI。

# --------------------------------------------------------------------
#   redis01.jl
#
#                       Jan/09/2022
# --------------------------------------------------------------------
using Genie
using Genie.Router
using Genie.Renderer.Json
using Genie.Requests
using Redis

# --------------------------------------------------------------------
function redis_get(key_in)
    conn = RedisConnection()
    str_json = get(conn, key_in)
    disconnect(conn)
#
    str_json
end

# --------------------------------------------------------------------
function redis_list()
    conn = RedisConnection()
    set_keys = keys(conn,"t*")
    disconnect(conn)
#
    json(set_keys)
end

# --------------------------------------------------------------------
function redis_insert(key_in,value_in)
    conn = RedisConnection()
    set(conn,key_in,value_in)
    disconnect(conn)
#
    key_in
end

# --------------------------------------------------------------------
function launchServer(port)

    Genie.config.run_as_server = true
    Genie.config.server_host = "0.0.0.0"
    Genie.config.server_port = port
#
    println("port set to $(port)")

    route("/") do
        "Hello."
    end

    route("/redis_get", method = POST) do
        key = jsonpayload()["key"]
        redis_get(key)
#       "redis_get key = " * String(key)
    end

    route("/redis_list", method = POST) do
        redis_list()
    end

    route("/redis_insert", method = POST) do
#       "redis_list"
        key = jsonpayload()["key"]
        value = jsonpayload()["value"]
        redis_insert(key,value)
    end

    Genie.AppServer.startup()
end

# --------------------------------------------------------------------
launchServer(parse(Int, ARGS[1]))

# --------------------------------------------------------------------

启动服务器

julia redis01.jl 8000

客户的访问

钥匙清单

$ http POST http://127.0.0.1:8000/redis_list/
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Genie/Julia/1.7.1
Transfer-Encoding: chunked

[
    "t1855",
    "t1857",
    "t1853",
    "t1854",
    "t1852",
    "t1859",
    "t1856",
    "t1858",
    "t1851"
]

通过指定键获取值

$ http POST http://127.0.0.1:8000/redis_get/ key=t1852
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Genie/Julia/1.7.1
Transfer-Encoding: chunked

{
    "date_mod": "2013-1-16",
    "name": "敦賀",
    "population": 17395
}

插入值 zhí)

$ http POST http://127.0.0.1:8000/redis_insert/ key=t1853 value='{"name": "宇都宮","population": 8751600,"date_mod": "2021-3-17"}'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Genie/Julia/1.7.1
Transfer-Encoding: chunked

t1853
广告
将在 10 秒后关闭
bannerAds