How to serialize / deserialize an Ecto model with the Loaded association?

I get User (with profile association, etc.) from the database for almost every request. I would like to cache on the server and store additional work in the database. The original thinking is Redis or Memcached and, ultimately, the distributed cache supported by Mnesia.

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

+5
source share
1 answer

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

A 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 in almost everything (I think!).

In Redis, in particular, you can send directly raw binary data to a Redis server and convert it back to Elixir data structures after they return from the server (again, like binary data). Here is 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"} 
+11
source

Source: https://habr.com/ru/post/1211731/


All Articles