Cloudflare Workersでサーバレス開発 part3 Workers KVを無料で使う

引き続きCloudflare Workersの話。今月、ありがたいことにCloudflare Workers KVのFree Tierが拡大されたようです。

今までは動作確認程度しか使えませんでしたが、無料枠が拡大されたことによりコンテンツキャッシュとして使えそうかなという感じです。AWSでいうところのLambda + DynamoDBの組み合わせをCloudflareの無料枠でも実現できるようになります。もちろんまだAWSと比べると細かい設定はできないどころか容量も桁違いに少ないですが、用途の限定すれば使い途はあるのではないでしょうか。

Workers KVの無料枠制限の内容だけ抜粋すると以下のようになります。

  • 1日10万回の読み取り操作
  • 1日1万回の書き込み、削除、リスト操作
  • 最大バリューサイズ25MB

Cloudflareのブログ内では書き込みが1日1000回となっていましたが、実際の制限は10000回かと思われます(ダッシュボード上では10000回になっている、要確認)。また、最大バリューサイズ(1つのキーに保存できるデータ容量)が10MBから25MBに引き上げられたことで巨大なアセットでも保存できるようになりました。25MBもあれば十分ですね。

環境構築

過去のエントリーを参考にしていただければ。今回もJavaScriptでWorkerを作っていきます。

* wrangler
wrangler 1.1x系だと絵文字たくさんですね。意味分かりませんが。

👷 ✨  wrangler 1.12.2
The Wrangler Team 

USAGE:
    wrangler [SUBCOMMAND]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

SUBCOMMANDS:
    kv:namespace    🗂️  Interact with your Workers KV Namespaces
    kv:key          🔑  Individually manage Workers KV key-value pairs
    kv:bulk         💪  Interact with multiple Workers KV key-value pairs at once
    route           ➡️  List or delete worker routes.
    secret          🤫  Generate a secret that can be referenced in the worker script
    generate        👯  Generate a new worker project
    init            📥  Create a wrangler.toml for an existing project
    build           🦀  Build your worker
    preview         🔬  Preview your code temporarily on cloudflareworkers.com
    dev             👂  Start a local server for developing your worker
    publish         🆙  Publish your worker to the orange cloud
    config          🕵️  Authenticate Wrangler with a Cloudflare API Token or Global API Key
    subdomain       👷  Configure your workers.dev subdomain
    whoami          🕵️  Retrieve your user info and test your auth config
    tail            🦚  Aggregate logs from production worker
    login           🔓 Authenticate Wrangler with your Cloudflare username and password
    help            Prints this message or the help of the given subcommand(s)

Cloudflare Workers KV

まずはwranglerでネームスペースを作ります。

wrangler-kv:namespace 
🗂️  Interact with your Workers KV Namespaces

USAGE:
    wrangler kv:namespace 

FLAGS:
    -h, --help    Prints help information

SUBCOMMANDS:
    create    Create a new namespace
    delete    Delete namespace
    help      Prints this message or the help of the given subcommand(s)
    list      List all namespaces on your Cloudflare account

## 作業ディレクトリ(wrangler.tomlの置いてあるディレクトリ)で実行
## "test"ネームスペースを作成
$ wrangler kv:namespace create test
🌀  Creating namespace with title "hello-test"
✨  Success!
Add the following to your configuration file:
kv_namespaces = [ 
         { binding = "test", id = "4c8cd836b9bc4eb4ab41a64366801e91" }
]

wrangler.tomlへの反映

ネームスペースを作成したら忘れないように wrangler.toml にも記載しておきます。

name = "hello"
type = "javascript"
account_id = {your account ID}
workers_dev = true
## 以下を追加
kv_namespaces = [
  {binding = "test", id = "4c8cd836b9bc4eb4ab41a64366801e91"}
]

[env.production]
route = "rest-term.com/worker/hello"
zone_id = {Zone ID}

Workers KVには任意の静的ファイルやJSONデータを入れることができます。ここでは適当なテキストファイルを保存してみます。

wrangler-kv:key 
🔑  Individually manage Workers KV key-value pairs

USAGE:
    wrangler kv:key 

FLAGS:
    -h, --help    Prints help information

SUBCOMMANDS:
    delete    Delete a key and its value from a namespace
    get       Get a key's value from a namespace
    help      Prints this message or the help of the given subcommand(s)
    list      List all keys in a namespace. Produces JSON output
    put       Put a key-value pair into a namespace

## 適当なファイル hello_kv.txt を作成
$ echo "hello, cloudflare workers kv" > hello_kv.txt
## test_key というキーでhello_kv.txtを保存
$ wrangler kv:key put test_key ./hello_kv.txt --path --binding test
✨  Success
## 正常に保存されたか確認
$ wrangler kv:key get test_key --binding test
hello, cloudflare workers kv

ファイルの中身を保存したい場合はpathオプションが必要です。bindingオプションにはネームスペース名を指定します。

JavaScriptからWorkers KVへのアクセス

Workers KVのネームスペースがそのままJavaScriptオブジェクトになっていて、get/put/delete メソッドが提供されています。

// Workers KVの動作確認のための簡易コード
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})
/**
 * Respond with hello worker text
 * @param {Request} request
 */
async function handleRequest(request) {
  // namespace: test, key: test_key でKVからデータ取得
  const content = await test.get("test_key");
  return new Response(content, {
    headers: { 'content-type': 'text/plain' },
  })
}

ここではデータ登録処理は省略しますが、await test.put("test_key", "test_value") のようにputメソッドを呼ぶだけです。オブジェクトそのものは保存できないので、JSON.stringify()などで文字列にシリアライズしてから保存します。注意点として、ネームスペース名は他の変数とコンフリクトしないように注意して付けないといけませんね。チュートリアルにあるように大文字にした方がわかりやすいかも。

workers.devに反映

開発環境(workers.dev)にデプロイします。前回はGitHub Action経由でデプロイしたんですが今回はコマンドから直接デプロイします。

$ wrangler publish
✨  JavaScript project found. Skipping unnecessary build!
✨  Successfully published your script to
 https://hello.wellflat.workers.dev

表示されたURLにブラウザからアクセスして、”hello, cloudflare workers kv” が表示されたらOKです。簡単ですね。

おわりに

今回はCloudflare Workers KVの使い方を紹介しました。機能的にはシンプルなKVSなので目新しさはありませんが、Worker環境に無料枠のストレージ層が新たに拡大されてサーバレス環境で開発する動機付けがより強くなるのではないでしょうか。

あわせて読む:

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です