首页 > 解决方案 > 连接到 R 中的 redis 集群

问题描述

假设redis服务器有几个主机和端口,比如

10.0.1.1:6381

10.0.1.1:6382

10.0.1.2:6381

10.0.1.2:6382

我该如何配置redux::hiredis()

我有谷歌,但找不到解决方案。而且我注意到函数db的参数上有一个注释redis_config“不要在redis集群上下文中使用。”,所以我想知道这是连接到集群的一种方式。另外,我也尝试过传递redis://10.0.1.1:6381,10.0.1.1:6382,10.0.1.2:6381,10.0.1.2:6382参数url,但还是失败了。

有什么建议么?或者有没有其他推荐的套餐?

标签: rredis

解决方案


我最初的解决方案是编写一个函数来根据错误消息指向正确的节点。

check_redis <- function(key = "P10000", host = "10.0.1.1", port = 6381) {
  r <- redux::hiredis(host = host, port = port)
  status <- tryCatch(
    {
      r$EXISTS(key = key)
    },
    error = function(e){
      address <- str_match(e$message, 
                           "[0-9]+.[0-9]+.[0-9]+.[0-9]+:[0-9]+")
      host <- str_split(address, ":", simplify = T)[1]
      port <- str_split(address, ":", simplify = T)[2]
      return(list(host = host, port = port))
    }
  )
  if (is.list(status)) {
    r <- redux::hiredis(host = status$host, port = status$port)
  } 
  return(r)
}

它可以帮助引导到正确的节点,但这种解决方案既不优雅也不高效。所以请指教。


推荐阅读