LoginSignup
2
1

More than 3 years have passed since last update.

Rust: Rocket で Redis のデータを読む

Posted at

Redis に次のようにデータが入っている時のデータを読みます。

$ redis-cli
127.0.0.1:6379> keys *
1) "t1857"
2) "t1859"
3) "t1855"
4) "t1853"
5) "t1858"
6) "t1854"
7) "t1856"
8) "t1851"
9) "t1852"
127.0.0.1:6379>

プロジェクトの作成

cargo new redis-cities --bin
cd redis-cities

次のファイルを作成します。

Cargo.toml
[package]
name = "backend"
version = "0.1.0"
edition = "2018"

[dependencies]
rocket = "0.4.5"

[dependencies.rocket_contrib]
version = "0.4.5"
default-features = false
features = ["redis_pool"]
Rocket.toml
[global.databases]
cities = { url = "redis://127.0.0.1:6379" }
src/main.rs
// --------------------------------------------------------------------
/*
    redis-cities/src/main.rs

                    Sep/20/2020
*/
// --------------------------------------------------------------------
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;

use std::io::Cursor;

use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket::http::ContentType;

use rocket_contrib::databases::redis::{self, Commands};

// --------------------------------------------------------------------
#[database("cities")]
struct CitiesDbConn(redis::Connection);

struct Cities {
  destination: String,
}

// --------------------------------------------------------------------
impl<'r> Responder<'r> for Cities {
  fn respond_to(self, _: &Request) -> response::Result<'r> {
    Response::build()
      .sized_body(Cursor::new(format!("{}", self.destination)))
      .header(ContentType::new("text", "plain"))
      .ok()
  }
}

// --------------------------------------------------------------------
#[get("/api/<id>")]
fn lookup(conn: CitiesDbConn, id: String) -> Option<Cities> {
    match conn.get(&id) {
    Ok(value) => Some(Cities {destination: value}),
    Err(_e) => None,
    }
}



// --------------------------------------------------------------------
fn main() {
  rocket::ignite()
  .attach(CitiesDbConn::fairing())
  .mount(
    "/",
    rocket::routes![lookup]
    )
  .launch();

}

// --------------------------------------------------------------------

コンパイル

cargo build

サーバーの実行

cargo run

テスト

$ curl http://localhost:8000/api/t1851
{"date_mod":"1956-6-9","name":"福井","population":53921}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1