如何使用Erlang等功能语言中的缓存数据? [英] How does one use cached data in a functional language such as Erlang?

查看:245
本文介绍了如何使用Erlang等功能语言中的缓存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在阅读有关功能语言的内容。来自10多年的OO开发,我发现很难让我的头脑在全球范围内可以指出纯功能方法(即同样的方法调用相同的参数也是一样的事情)在通常(在OO程序中)我需要缓存数据的问题。




  • 我们只是承认,程序中可能需要一个不是不可变的(即缓存)的actor。我刚刚看到一个 Joe Armstrong在infoq上的演示,他似乎很教条在这方面!


  • 我们只承认查找数据可能很昂贵(因为我们永远不能缓存)?如果是这样,我们如何控制一些共享资源(例如数据库)上的负载。


  • 是否有一些神奇的童话尘埃不知道怎么解决这个问题,然后再喝一杯茶。




谷歌搜索Erlang Cache似乎返回一个很少的结果...

解决方案

这是必须是不可变的数据长长的演员通常生活在一个尾递归函数中,它们的参数作为它们的状态,当然可以在调用之间改变。



p>

  -module(cache)。 
-export([start / 0,get_c / 1,put_c / 2,clear / 1])。

start() - > register(spawn(fun() - > loop(dict:new())end),cache)。

loop(Dict) - >接收
{get,From,Key} - >从! {cache_result,Key,dict:fetch(Key,Dict)};
{set,Key,Value} - > NewDict = dict:store(Key,Value,Dict),
loop(NewDict);
%%等
end

put_c(Key,Value) - >缓存! {set,Key,Value}
%%等

当您调用 put_c ,即使涉及的所有数据都是不可变的,演员的状态也会发生变化。


I've been reading a bit lately about functional languages. Coming from 10+ years of OO development, I'm finding it difficult to get my head around how on earth one can point the pure functional approach (i.e. the same method called with the same parameters does the same thing) at a problem where typically (in an OO program) I would need to cache data.

  • Do we just admit that there might need to be an actor in the program which is not immutable (i.e. the cache). I just watched a presentation by Joe Armstrong on infoq and he seemed pretty dogmatic in this regard!

  • Do we just admit that looking up data might be expensive (because we can never cache it)? If so, how can we control, for example, the load on some shared resource (e.g. a database)

  • Is there some magic fairy dust, which I don't know about yet, which solves the whole problem and then makes a nice cup of tea afterwards.

Certainly a google search for "Erlang Cache" seems to return a fair few results...

解决方案

It is data which must be immutable in Erlang, not actors.

Long-lived actors normally live in a tail-recursive function, the arguments of which serve as their state and certainly can change between calls.

-module(cache).
-export([start/0, get_c/1, put_c/2, clear/1]).

start() -> register(spawn(fun () -> loop(dict:new()) end), cache).

loop(Dict) -> receive
                {get, From, Key} -> From ! {cache_result, Key, dict:fetch(Key, Dict)};
                {set, Key, Value} -> NewDict = dict:store(Key, Value, Dict),
                                     loop(NewDict);
                %% etc.
              end

put_c(Key, Value) -> cache ! {set, Key, Value}
%% etc.

When you call put_c, the actor's "state" changes even though all data involved is immutable.

这篇关于如何使用Erlang等功能语言中的缓存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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