Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize/deserialize Ecto model with Loaded associations?

Tags:

elixir

ecto

I'm fetching User (with Profile association, etc) from the database on almost every request. I would like to cache on the server and save the database some extra work. Initially thinking Redis or Memcached and eventually a distributed cache backed by Mnesia.

I know how to do the transport (of a binary in the case of Redis/Memcache to the caching backends) but how do I serialize and deserialize the model to a binary?

like image 979
Krut Avatar asked Jan 22 '15 21:01

Krut


1 Answers

You can try using the :erlang.term_to_binary/1 and :erlang.binary_to_term/1 functions (small bits of documentation here).

Small example:

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}

It should work with pretty much everything (I think!).

In Redis in particular, you can send directly raw binary data to the Redis server and convert them back to Elixir data structures after fetching them back from the server (again as binary data). Here's a small example (using 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"}
like image 135
whatyouhide Avatar answered Nov 09 '22 02:11

whatyouhide