Help us understand the problem. What is going on with this article?

シェルスクリプトからmemcachedを使う

More than 1 year has passed since last update.

シェルスクリプトの中でmemcachedを使うためのライブラリ的なものを作りました。シェルスクリプトにincludeして使うことを想定しています。エラー処理とかテストとか不十分なので、まだPoCレベルなことをご了承ください。

前提条件

telnetが無ければインストールしておいてください。あと、もちろんmemcachedを起動しておいてください。

ソースコード

memcached.sh
MC_HOST="localhost"
MC_PORT="11211"

mc_open() {
  coproc mc { telnet ${MC_HOST} ${MC_PORT}; } 2>/dev/null
  # telnet接続時の出力を3行分読み飛ばす
  read <&"${mc[0]}"    # Trying ::1...
  read <&"${mc[0]}"    # Connected to localhost.
  read <&"${mc[0]}"    # Escape character is '^]'.
}

mc_set() {
  local r
  echo "set ${1} 0 ${2} ${#3}" >&"${mc[1]}"
  echo "${3}" >&"${mc[1]}"
  read r <&"${mc[0]}"
  if [ "${r}" = "STORED" ]; then
    return 0
  else
    echo ${r} >&2
    return 1
  fi
}

mc_get() {
  local i r v
  echo "get ${1}" >&"${mc[1]}"
  for i in {0..2}      # 値があれば3行目、無ければ1行目が"END"
  do
    read r <&"${mc[0]}"
    if [ "${r}" = "END" ]; then
      echo -n ${v}
      break
    else
      v=${r}
    fi
  done
  return 0
}

mc_close() {
  echo "quit" >&"${mc[1]}"
}

使い方

sample.sh
#!/bin/sh
. ./memcached.sh

# 接続開始
mc_open

# 値のsetは キー 有効期間 値 を指定
mc_set mykey1 10 myvalue1

# 値のgetは キー を指定
v1=$(mc_get mykey1)
echo "Value of mykey1 is ${v1}."

# 値をsetしてないキーでgetすると、結果は空文字
v2=$(mc_get mykey2)
if [ "${v2}" = "" ]; then
  echo "Value of mykey2 is empty."
else
  echo ${v2}
fi

# 接続終了
mc_close

今後

memcachedが使えると、分散処理、並列処理などへの応用が可能になります。今後、使ってみながらブラッシュアップしていきます。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした