Skip to content

Instantly share code, notes, and snippets.

@blainsmith
Last active April 4, 2018 18:06
Show Gist options
  • Save blainsmith/382699d8c158b586284124adca039ae0 to your computer and use it in GitHub Desktop.
Save blainsmith/382699d8c158b586284124adca039ae0 to your computer and use it in GitHub Desktop.
Go and C Redis Pub/Sub
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <hiredis/hiredis.h>
int main(int argc, char **argv) {
unsigned int j;
redisContext *c;
redisReply *reply;
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
int port = (argc > 2) ? atoi(argv[2]) : 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
int ts;
for (;;) {
ts = (unsigned)time(NULL);
printf("Sending %d\n", ts);
reply = redisCommand(c, "PUBLISH %s %d", "i2c.burst", ts);
freeReplyObject(reply);
sleep(1);
}
redisFree(c);
return 0;
}
package main
import (
"flag"
"log"
"time"
"github.com/gomodule/redigo/redis"
)
func main() {
var delay = flag.Int("delay", 1000, "delay in milliseconds")
flag.Parse()
c, err := redis.Dial("tcp", ":6379")
if err != nil {
// handle error
}
defer c.Close()
var ts int64
for {
ts = time.Now().UnixNano() / int64(time.Millisecond)
log.Println("Sending", ts)
c.Send("PUBLISH", "i2c.burst", ts)
c.Flush()
time.Sleep(time.Duration(*delay) * time.Millisecond)
}
}
package main
import (
"log"
"github.com/gomodule/redigo/redis"
)
func main() {
c, err := redis.Dial("tcp", ":6379")
if err != nil {
// handle error
}
defer c.Close()
psc := redis.PubSubConn{Conn: c}
psc.Subscribe("i2c.burst")
for {
switch v := psc.Receive().(type) {
case redis.Message:
log.Printf("%s: message: %s\n", v.Channel, v.Data)
case redis.Subscription:
log.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
log.Fatal(v)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment