A way to get-things-going is:
- Create a
gen_server
which you add to the supervisor tree of an application. Preferably your own application which you include. - When the
gen_server
initializes, it sets up a Riak connection. Whenever you want to use the connection, youcall
thegen_server
and since it has the connection, it will be able to issue queries. - Handle reconnects. If the connection is lost, you crash the
gen_server
. If the connection is refused upon initialization, you wait a bit and try again.
Often, you will see a separate application running the "backend" stuff of an Erlang system and then another application, like nitrogen, to handle the Web-stuff. Your gen_server
would belong to the "backend" part.
Once this basis works you can extend it further:
- Your gen_server will be living in a module named
foo
. Whenever you want to use riak, you callfoo:f(...)
. Rewritefoo:f(...)
to use http://github.com/devinus/poolboy or something such to support connection pooling toward the Riak cluster. But only do this once it proves that a single connection is too slow.
This neatly shows the idea of loose coupling in Erlang programs. The foo
module acts like an interface, but you don't know the implementation behind that interface. You can change it later for something faster should the need arise. The only thing you need to do is to implement the correct protocol, which is a function call in this case.