运行Redis 3.2.1和最新的Hedis库,我具有以下发布程序:

{-# LANGUAGE OverloadedStrings #-}
module Main where

import Database.Redis
import Control.Monad
import Control.Concurrent
import Control.Monad.Trans
import Data.ByteString as BS
import System.Posix.Process
import Data.String.Conv

main :: IO ()
main = do
  conn <- connect defaultConnectInfo
  runRedis conn run

run = do
    liftIO $ threadDelay $ 1000 * 1000
    pid <- liftIO getProcessID
    publish "chan1" (toS $ show pid)
    publish "chan2" (toS $ show pid)
    liftIO $ Prelude.putStrLn "\n\n%%%%%%%\n\nnext\n\n%%%%%%%%\n\n"
    run

订户看起来像这样:
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Database.Redis

main :: IO ()
main = do
  conn <- connect defaultConnectInfo
  runRedis conn $ do
    pubSub (subscribe ["chan1"]) $ \msg -> do
      putStrLn $ "chan1 " ++ show (msgChannel msg) ++ ": " ++ show (msgMessage msg)
      return mempty
    pubSub (subscribe ["chan2"]) $ \msg -> do
      putStrLn $ "chan2" ++ show (msgChannel msg) ++ ": " ++ show (msgMessage msg)
      return mempty

输出为:
%%%%%%%

next

%%%%%%%%

chan1 "chan1": "21542"

%%%%%%%

next

%%%%%%%%

chan1 "chan1": "21542"

%%%%%%%

next

%%%%%%%%

chan1 "chan1": "21542"

%%%%%%%

next

%%%%%%%%

现在看来,订户一旦阅读了第一个 channel ,发送到第二个 channel 的消息就不会被阅读。换句话说,似乎忽略了订阅chan2的命令。

为了完整起见,这是我的Cabal文件:
name:                pub-sub-exp
version:             0.1.0.0
synopsis:            Simple project template from stack
description:         Please see README.md
homepage:            https://github.com/githubuser/pub-sub-exp#readme
license:             BSD3
license-file:        LICENSE
author:              Author name here
maintainer:          [email protected]
copyright:           2016 Author name here
category:            Web
build-type:          Simple
cabal-version:       >=1.10

executable pub
  hs-source-dirs:      src
  main-is:             Pub.hs
  default-language:    Haskell2010
  build-depends:       base >= 4.7 && < 5,
                       hedis,
                       mtl,
                       bytestring,
                       unix,
                       string-conv

executable sub
  hs-source-dirs:      src
  main-is:             Sub.hs
  default-language:    Haskell2010
  build-depends:       base >= 4.7 && < 5,
                       hedis,
                       mtl,
                       bytestring

我正在使用stack-lts-6.6

为了澄清起见,我希望订户指出消息已发送到通道1和2。

这是Redis的知名属性(property)吗?我想念一些Haskell陷阱吗?

最佳答案

您需要在一个操作中同时订阅两个 channel 。

pubSub (subscribe ["chan1", "chan2"]) $ \msg -> do

Hedis没有接通您的第二个pubSub电话。从 pubSub 's definition中可以看到,除非订阅计数和挂起的消息都被耗尽,否则该函数将不会返回。还要注意,没有 fork 或其他启用并发的方法。

关于haskell - 如何在同一功能中订阅多个Redis channel ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38228263/

10-15 07:12