【发布时间】:2020-06-01 08:54:57
【问题描述】:
我想从我的 Phoenix 应用程序连接到 Redis,但无法这样做。
我正在使用 Phoenix v1.3.0 。我安装了 Redix 包。在 lib/myapp.ex 我有以下代码
defmodule myapp do
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Get all configuration used for Cache module
pool_size = Application.get_env(:myapp, :redis_pool_size)
redis_host = Application.get_env(:myapp, :redis_host)
redis_port = Application.get_env(:myapp, :redis_port)
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(myapp.Repo, []),
# Start the endpoint when the application starts
supervisor(myapp.Endpoint, []),
#Start redis supervisor
supervisor(myapp.Cache.Supervisor, [
%{
pool_size: pool_size,
host: redis_host,
port: redis_port
}
])
# supervisor(Kafka.Endpoint, [])
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: myapp.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
myapp.Endpoint.config_change(changed, removed)
:ok
end
end
在 lib/myapp/cache/cache.ex 中,我有,
defmodule MyApp.Cache do
require Logger
def setex(segment, key, value, ttl \\ nil) do
ttl = ttl || get_default_ttl()
pid = get_pid()
key = build_key(segment, key)
command = ["SETEX", key, ttl, value]
run_command(pid, command)
end
def get(segment, key) do
pid = get_pid()
key = build_key(segment, key)
command = ["GET", key]
run_command(pid, command)
end
def flush_all do
pid = get_pid()
command = ["FLUSHALL"]
run_command(pid, command)
end
defp get_default_ttl(), do: Application.get_env(:myapp, :redis_ttl)
defp get_app_name(), do: Application.get_env(:myapp, :app_name)
defp get_pool_size(), do: Application.get_env(:myapp, :redis_pool_size)
defp build_key(segment, key), do: "#{get_app_name()}:#{segment}-#{key}"
defp get_pid, do: :"redix_#{random_index()}"
defp random_index(), do: rem(System.unique_integer([:positive]), get_pool_size())
defp run_command(pid, command) do
Logger.debug("Running command: #{inspect(command)} in Redis")
Redix.command(pid, command)
end
end
在 lib/myapp/cache/supervisor.ex 中,我有,
defmodule MyApp.Cache.Supervisor do
use Supervisor
def start_link(opts) do
Supervisor.start_link(__MODULE__, opts, name: __MODULE__)
end
def init(%{
pool_size: pool_size,
host: host,
port: port
}) do
children =
for i <- 0..(pool_size - 1) do
Supervisor.child_spec(
{Redix, [host: host, port: port, name: :"redix_#{i}"]},
id: {Redix, i}
)
end
Supervisor.init(children, strategy: :one_for_one)
end
end
现在,当我运行 MyApp.get("1", "2") 时,出现以下错误:
(ArgumentError) 参数错误 (stdlib) :ets.lookup(:telemetry_handler_table, [:redix, :pipeline])
我签入了 Redis,键和值确实存在。我该如何解决这个问题?
谢谢
【问题讨论】:
-
请编辑您的问题并添加您的
mix.exs文件。