如何使用Loaded关联序列化/反序列化Ecto模型?

时间:2015-01-22 21:12:24

标签: elixir ecto

我几乎在每个请求中都从数据库中获取用户(带有配置文件关联等)。我想缓存在服务器上并保存数据库一些额外的工作。最初考虑Redis或Memcached,最后是由Mnesia支持的分布式缓存。

我知道如何传输(在Redis / Memcache的情况下将二进制文件传输到缓存后端)但是如何将模型序列化和反序列化为二进制文件?

1 个答案:

答案 0 :(得分:13)

您可以尝试使用:erlang.term_to_binary/1:erlang.binary_to_term/1函数(少量文档here)。

小例子:

iex> defmodule FooStruct do
...>   defstruct foofield: nil
...> end
iex> struct = %FooStruct{foofield: 42}
iex> binary_representation = :erlang.term_to_binary(struct)
<<131, 116, 0, 0, 0, 2, 100, 0 ... >>
iex> :erlang.binary_to_term(binary_representation)
%FooStruct{foofield: 42}

它应该适用于所有的东西(我想!)。

特别是在Redis中,您可以直接将原始二进制数据发送到Redis服务器,并在从服务器获取它们之后将它们转换回Elixir数据结构(再次作为二进制数据)。这是一个小例子(使用exredis):

iex> client = Exredis.start
iex> data = :erlang.term_to_binary(%{foo: "bar"})
<< ... >>
iex> client |> Exredis.query(["SET", "mymap", data])
"OK"
iex> retrieved_data = client |> Exredis.query(["GET", "mymap"])
<< ... >>
iex> :erlang.binary_to_term(retrieved_data)
%{foo: "bar"}
相关问题