How can I make Webmachine and eredis work together

2019-04-13 06:59发布

问题:

I've been meditating on the question of Redis usage in my Webmachine application for a week. And I haven't enlightened yet.

I'm going to use Eredis and here is an example of usage:

{ok, Con} = eredis:start_link().

{ok, <<"OK">>} = eredis:q(Con, ["SET", "foo", "bar"]).
{ok, <<"bar">>} = eredis:q(Con, ["GET", "foo"]).

As I understand eredis:start_link() should be called somewhere only once. But then how can I get Con variable in my resources?

回答1:

There are several solutions:

  • register a redis connection locally or globally
  • use a process register like gproc
  • keep the pid of the connection in the webmachine resource context
  • use a connection pool like pooler or poolboy
  • in case you don't want to queue requests in a pool dispcount could fit

Edit: misunderstood question, first answer below:

Webmachine and eredis are both Erlang applications following the OTP principles. If your application is OTP conform you can add eredis to the applications in your .app file, like the following:

{application, awesome_app, [
    {description, "My awesome app."},
    {vsn, "0.0.1"},
    {modules, []},
    {registered, []},
    {applications, [kernel, stdlib, 
                    eredis, 
                    webmachine]}
]}.

OTP conform applications use releases. After you create a release and start your application the applications in applications will be started before your app.

Rebar is your friend for building and generating releases (more info here). An alternative to rebar is sinan which is described in this article.