如何在Elixir模块中创建全局变量 [英] How to create a Global Variable in elixir Module

查看:82
本文介绍了如何在Elixir模块中创建全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在长生不老药中有以下代码:

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

现在,现在许多函数正在调用get_trackerid函数,每次该函数被调用时

Now, now many functions are calling get_trackerid function and everytime the function is called, a call to database is made.

有没有一种方法可以在Elixir中编写函数,从而将结果存储在局部变量中。因此,当下一次请求相同imei的trackerid时,我可以从局部变量本身获取数据。

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?

推荐答案

您可以在Elixir中保存一些状态。

You have a few options for saving state within Elixir.

如果此方法是运行 GenServer ,则可以使用 state 参数来缓存值。

If this method is part of a module that is running a GenServer, then you can use the state parameter to cache values.

您也可以使用 ets表来缓存值。这将在GenServer内部和外部都起作用。

You could also use an ets table to cache the values. This would work both inside and outside a GenServer.

这篇关于如何在Elixir模块中创建全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆