LoginSignup
6
6

More than 5 years have passed since last update.

Redis 最短入門(2)5分でAPI

Last updated at Posted at 2016-01-05

なにも考えずにAPIとして使ってみるまで5分。
コードコピペしてもらえると、コマンドで7行くらい。

node.jsとnpm (node.jsのパッケージ管理ツール)のインストール

sudo yum install -y nodejs npm --enablerepo=epel

APIサーバーの作成

パッケージ用にディレクトリ作成

mkdir myapi ; cd myapi

ディレクトリ内で初期設定、サーバー機能 express とredisクライアントをインストール

npm init
npm install express --save
npm install redis --save

index.js(下記)
まず、シンプルに /item/"key" として、"key" に登録しているキーを指定したら値をJSONで返すAPIを作成します。

※ポート番号がすでにつかっていたら(apacheがインストールされてる)一番下のポート番号を変えてください

※下準備として Redis 最短入門(1) でサーバーを起動し、値をセットしておいてください

SET "key" "value"

※"key" と "value" は任意の値

起動させる(http サーバーが立ち上がるので、バックエンドで)

node index.js &

http:// IPアドレス : ポート番号/item/"somekey" でレスポンス確認

curl http://0.0.0.0:8880/item/"key"

→ 下準備で登録したキー "key" の値(string)を JSON形式 {"item":value} で返却されます

app.get('/get/:id',... のところが URL
var server = app.listen(8880, function () {..}
のところがポート番号になります

終了はおもむろにkillしてください

ソースコード例

index.js

var express = require('express');
var app = express();

app.get('/item/:id', function (request, response) {

    var client = require('redis').createClient();
    var id = request.params.id;

    client.get(id, function (err, res) {
        if (err) {
            return console.log(err);
        } else {
            console.log(res);
            response.send(JSON.stringify({'item':res}));
        }
    });


});

app.get('/', function (req, res) {
    res.send('Hello World!');
});

var server = app.listen(8880, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});
6
6
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
6
6