LoginSignup
3
3

More than 5 years have passed since last update.

ClojureでMessagePackを使う

Last updated at Posted at 2014-08-09

clojure使いはアプリケーション間やWebAppのクライアント-サーバー間のデータのやり取りにednを使う場合が多いかと思います。
ただ、異なる言語で書かれたアプリケーション間でデータをやり取りする場合やネットワーク通信量、シリアライズに必要なコストを抑えたい場合はMessagePackを使うのが良さそうです。

準備

clojureにはclojure-msgpackというライブラリがあるのでこれを利用します。
leiningenで新たにプロジェクトを作り、project.cljのdependenciesに追加します。

(defproject test_messagepack "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [clojure-msgpack "0.1.0-SNAPSHOT"]])

replで試す

replを使ってgithubにあるUsageを試してみましょう。

$ lein repl

user=> (require '[msgpack.core :refer :all])
nil
user=> (pack {:compact true :schema 0})
#<byte [] [B@25bd137c>
user=> (defrecord Employee [name])
user.Employee
user=> (defext Employee 1 [e]
  #_=>   (.getBytes (:name e)))
nil

user=> (let [bob (Employee. "Bob")
  #_=>       bytes (pack bob)]
  #_=>   (map #(format "0x%x" %) bytes))
("0xc7" "0x3" "0x1" "0x42" "0x6f" "0x62")
user=> (pack (->Extension 1 (.getBytes "Bob")))
#<byte [] [B@49592ea1>

user=> (pack {:compact true :schema 0})
#<byte [] [B@8582ec6>

user=> (unpack (pack {:compact true :schema 0}))
{ "compact" true, "schema" 0}
user=>]]]

とても簡単。
基本的にpackしたbyte列をネットワーク等で送って、受け取った側でunpackすればよいようです。

TODO: ネットワークを使用したサンプルを書く。
TODO: jsonとの性能比較を検証する

ブラウザ等のクライアント側でunpackするにはjavascriptで以下のライブラリを使えばいいみたいです。
msgpack-javascript

3
3
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
3
3