问题
I have the following code in elixir:
def get_trackerid(imei) do
client = get_new_client()
{:ok, result} = :cqerl.run_query(client, "SELECT * FROM trackers_by_imei where imei = \'#{imei}\';")
row = :cqerl.all_rows(result)
end
Now, now many functions are calling get_trackerid function and everytime the function is called, a call to database is made.
Is there a way to write a function in elixir such the result is stored in a local variable. So, when the next time trackerid for the same imei is requested, I can get the data from the local variable itself.
I think there is no concept of global variable in elixir, so that is not an option, right?
回答1:
You have a few options for saving state within Elixir.
If this method is part of a module that is running a GenServer, then you can use the state
parameter to cache values.
You could also use an ets table to cache the values. This would work both inside and outside a GenServer.
回答2:
What you're asking about is called "memoization". I mention that if you care to Google and see if you can find more on the subject.
This is a great blog posting discussing a memoization technique in Elixir: https://web.archive.org/web/20161116091132/http://ineverfinishanyth.in/2014/01/20/memoization-in-elixir
TL;DR
Construct a cache and check the cache when you try to do your computation to see if the answer is already there. In the case of that blog posting he constructs a key-value store as a cache but obviously what sort of cache you should construct will be highly dependent on the data you're caching.
来源:https://stackoverflow.com/questions/35465306/how-to-create-a-global-variable-in-elixir-module