0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rust: Redis のデータを更新 (Update)

Last updated at Posted at 2020-07-22

フォルダー構造

$ tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    └── debug
Cargo.toml
[package]
name = "redis_update"
version = "0.1.0"
edition = "2018"

#

[dependencies.redis]
version = "*"

[dependencies]
tokio = { version = "0.2", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
chrono = "0.4"
src/main.rs
// --------------------------------------------------------------------
/*
	redis_update/src/main.rs

					Jul/22/2020
*/
// --------------------------------------------------------------------
use std::env;
extern crate redis;
use redis::{Commands};
use chrono::{Local, Date};
use serde_json::json;

// --------------------------------------------------------------------
fn main() -> Result<(), Box<dyn std::error::Error>>  {
	eprintln! ("*** 開始 ***");

	let args: Vec<_> = env::args().collect();
	let key_in = &args[1];
	let population_in = &args[2];
	println! ("{}\t{}",key_in,population_in);

	let client = redis::Client::open("redis://localhost/").expect("url error");
	let mut conn = client.get_connection().expect("connect error");

	let res = conn.get(key_in.to_string());

	let answer: String = res.unwrap();

	let json: serde_json::Value = serde_json::from_str(&answer)?;

	let obj = json.as_object().unwrap();

	println! ("{}",obj["name"].to_string());
	println! ("{}",obj["population"].to_string());
	println! ("{}",obj["date_mod"].to_string());

	let date_mod: Date<Local> = Local::today();
	println!("{}", date_mod);

	let pp_in : i32 = population_in.parse().unwrap();
	let obj_new = json!({
		"name": obj["name"],
		"population": pp_in,
		"date_mod": date_mod.to_string()
		});

	let json_str = obj_new.to_string();
	println!("{}",json_str);

	let _: ()  = conn.set(key_in.to_string(), json_str).unwrap();

	eprintln! ("*** 終了 ***");

	Ok(())
}

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

コンパイル

cargo build

実行

cargo run t1857 5128900
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?