在e剂中缓存昂贵的计算 [英] Caching expensive computation in elixir

查看:49
本文介绍了在e剂中缓存昂贵的计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在elixir中有一个如下所示的Web应用程序

I have an web application in elixir that looks like this

defmodule Test do
  use Plug.Router

  plug :match
  plug :dispatch

  def expensiveComputation() do
     // performs an expensive computation and
     // returns a list
  end

  get "/randomElement" do
    randomElement = expensiveComputation() |> Enum.random
    send_resp(conn, 200, randomElement)
  end

end

每当我向 / randomElement 发出 GET 请求时cheapComputation 被调用。 expensiveComputation 函数需要很长时间才能运行,但是每次调用都返回相同的结果。缓存结果以使其仅在启动时仅运行一次的最简单方法是什么?

Whenever I issue a GET request to /randomElement, expensiveComputation gets called. The expensiveComputation function takes a long time to run but returns the same thing every time it is called. What is the simplest way to cache the result so that it gets run only once on startup?

推荐答案

在Elixir中,当您需要状态时您几乎总是需要有一个流程来保持该状态。 Agent 模块特别适合您想要的那种操作-只需包装一些值并访问它即可。像这样的东西应该起作用:

In Elixir when you want state you almost always need to have a process to keep that state. The Agent module is particularly suited for the kind of operation you want - simply wrapping some value and accessing it. Something like this should work:

defmodule Cache do
  def start_link do
    initial_state = expensive_computation
    Agent.start_link(fn -> initial_state end, name: __MODULE__)
  end

  def get(f \\ &(&1)) do
    Agent.get(__MODULE__, f)
  end

  defp expensive_computation do
    # ...
  end
end

然后,您可以正常地将 Cache 插入您的监督树,而只需 Cache.get ,当您需要 expensive_computation 的结果时。

Then you can plug in Cache into your supervision tree normally, and just Cache.get when you need the result of expensive_computation.

请注意,这实际上会在启动时运行 expensive_computation -在启动监管树的过程中。如果非常昂贵-大约10秒或更长时间-您可能希望将计算移至 Agent 进程:

Please note that this will literally run expensive_computation on startup - in the process bringing up your supervision tree. If it is very expensive - on the order of 10 seconds or more - you might want to move the computation to the Agent process:

def start_link do
  Agent.start_link(fn -> expensive_computation end, name: __MODULE__)
end

在这种情况下,您需要处理缓存为空的情况,而在第一个示例中,启动是直到 expensive_computation 完成为止。您可以通过在启动顺序的后面根据 Cache 放置工作线程来使用它。

You need to handle the case of the cache being empty in that case, while in the first example the startup is blocked until expensive_computation is finished. You can use it by placing workers depending on the Cache later in the startup order.

这篇关于在e剂中缓存昂贵的计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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