fireproofsocks

fireproofsocks

Using Cachex in Phoenix - working example?

I’m new to Elixir and Phoenix and I’m trying to implement Cachex. I’m struggling to get this working. I added the dependency to my mix.exs and I modified my application function so it references the Cachex app:

def application do
    [
      mod: {MyApp.Application, []},
      extra_applications: [:logger, :runtime_tools],
      applications: [:cachex]
    ]
  end

deps.get downloaded the package and that all seems to be working.

In my application.ex, I have tried to add the appropriate block to the Supervisor.start_link:

  def start(_type, _args) do
    import Supervisor.Spec

    # Define workers and child supervisors to be supervised
    children = [
      supervisor(MyApp.Repo, []),
      supervisor(MyApp.Endpoint, []),
      worker(Cachex, [:my_cache, []]),
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
    
  end

As soon as I try to run the server, I get an error:

mix phx.server
Compiling 16 files (.ex)
Generated my_app app

=INFO REPORT==== 12-Feb-2018::15:32:28 ===
    application: logger
    exited: stopped
    type: temporary
** (Mix) Could not start application my_app: MyApp.Application.start(:normal, []) returned an error: shutdown: failed to start child: MyApp.Repo
    ** (EXIT) exited in: GenServer.call(Ecto.Registry, {:associate, #PID<0.367.0>, {MyApp.Repo, MyApp.Repo.Pool, [name: MyApp.Repo.Pool, otp_app: :my_app, repo: MyApp.Repo, timeout: 15000, pool_timeout: 5000, adapter: Ecto.Adapters.MySQL, username: "my_user", password: "xxxxx", database: "my_db", hostname: "my.host.tld", pool_size: 10, pool: DBConnection.Poolboy]}}, 5000)
        ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started

I’m not sure why it is choking. I can at least compile the app and start the server if I add :cachex to the “extra_applications” instead of to the “applications” bit. Can someone shed some light on this? Is it viable to use extra_applications instead?

Most Liked

outlog

outlog

try with Cachex.get - not sure a fetch exists - Cachex — Cachex v4.1.1

so maybe:

def get_cached_result!(slug) do

    Cachex.get(:my_cache, "key_#{slug}", fn(slug) ->
      Repo.get_by!(MyRecord, slug: slug, parent_id: 0)
    end)

end

fwiw I have this from some old code (untested recently):

{ _status, post } = Cachex.get(:my_cache, "post_#{id}", fallback: fn(_params) ->
  Post
  |> Repo.get!(id)
  |> Repo.preload([:comments])
end)

EDIT: from a quick look: fetch is being added in Cachex 3.0 - so thats probably why you find it on the github examples:/

fireproofsocks

fireproofsocks

Thank you for your patient guidance – it helps, and in retrospect, it all seems obvious.

outlog

outlog

it does blow up with a bang.. so a bit more defensive code is needed, unless you are doing bangs on purpose..

if you simply remove the bang and use get_by it will return nil on not found, and that will be cached - depending on your caching strategy you might not want that - and you can use the ignore feature.. that way the nil/not found is not cached and the db is always queried on slugs that are not found - but it all depends..

here is an example.. using :ignore so the nil is not cached.. else just remove the bang in get_by

  def get_cached_thing!(slug) do
    Cachex.get(
      :my_cache,
      slug,
      fallback: fn slug ->
        case result = Repo.get_by(Mything, id: slug) do
          %Mything{} ->
            # happy path - commit to cache
            {:commit, result}

          nil ->
            # not found - ignore tuple so it's not cached
            {:ignore, nil}
        end
      end
    )
    |> case do
      # It's not common to return error strings, rather you'd probably want an error tuple
      {:error, _} ->
        {:error, "error - devops needed?"}

      # the ignore returns an :loaded tuple - so match nil
      {:loaded, nil} ->
        {:error, :not_found}

      {success, result} when success in [:ok, :loaded] ->
        {:ok, result}
    end
  end

Last Post!

OvermindDL1

OvermindDL1

It’s in the error handling section of the phoenix docs, you can either explicitly state what error in the conn and then return the conn, or you can raise an exception that specifies to phoenix what error to return. :slight_smile:

Where Next?

Popular in Questions Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42533 114
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement