Skip to content
This repository has been archived by the owner on Dec 30, 2018. It is now read-only.

steelbrain/Async-Redis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Async-Redis

Async-Redis is a Redis Pub/Sub Client for HackLang. it makes use of HackLang's built-in async functions.

Usage

$RedisSub = new AsyncRedis('tcp://localhost:6379');
$RedisSub->subscribe('FirstChannel');
$RedisSub->subscribe('SecondChannel');
$RedisSub->OnMessage('FirstChannel', async function(string $Message){
  echo "First Channel $Message \n";
});
$RedisSub->OnMessage('SecondChannel', async function(string $Message){
  echo "Second Channel $Message \n";
});
$RedisSub->unsubscribe('FirstChannel');

HowTo

Because Async-Redis uses HHVM's WaitHandles, You'll have to join them to make sure the script doesn't kill the async function. Here's how you can do it

$RedisSub = new AsyncRedis('tcp://localhost:6379');
$RedisSub->subscribe('FirstChannel');
$RedisSub->OnMessage('FirstChannel', async function(string $Message){
  echo "Message: $Message \n";
});
$RedisSub->WaitHandle->join(); // This will stop the program from halting, because this is in infinite loop, the program won't go any further

As you can see in the example above, You can not continue your program and listen for messages at the same time, It kind-of becomes a blocking way. Therefore the solution I use is to make the init function of your Server Sided App an async one, so you can wait on both of them.

class MyServerSidedApp{
  public AsyncRedis $RedisSub;
  public function __construct(){
    $this->RedisSub = new AsyncRedis('tcp://localhost:6378');
    $this->RedisSub->subscribe('FirstChannel');
    $this->RedisSub->OnMessage('FirstChannel', async function(string $Message){
      echo "First Channel $Message \n";
    });
  }
  public async function Init():Awaitable<void>{
    // Do the regular app stuff here..
  }
}
$App = new MyServerSidedApp();
GenArrayWaitHandle::create([$App->RedisSub->WaitHandle, $App->Init()])->join();
// This way your program and the Redis subscriber will run co-currently

An extended version of this example can be found in Example.hh.

License

This project is licensed under the terms of MIT License. See the LICENSE file for more info.

About

Async Redis Pub/Sub in HackLang

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages