GoとRedisにおける簡単なチャットアプリケーション

Koya Suzuki
Dec 16, 2018 · 10 min read

紹介するRedisのtips

Redisのインストール

$ brew install redis

Redisに接続する

Redigoとは

// Connect using os.Getenv("REDIS_URL").
conn, err := redisurl.Connect()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

ユーザーの作成

userName := os.Args[1]
userKey := “online.” + userName

TTLとは

val, err := conn.Do(“SET”, userkey, username, “NX”, “EX”, “120”)
if val == nil {
fmt.Println(“既にオンラインです。”)
os.Exit(1)
}

ユーザーリストの設定

val, err = conn.Do(“SADD”, “users”, userName)
tickerChan := time.NewTicker(time.Second * 60).C

メッセージの送受信

subChan := make(chan string)
go func() {
subConn, err := redisurl.Connect()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer subConn.Close()
psc := redis.PubSubConn{Conn: subconn}
psc.Subscribe(“messages”)
for {
switch v := psc.Receive().(type) {
case redis.Message:
subChan <- string(v.Data)
case redis.Subscription:
break
case error:
return
}
}

ターミナルからコマンドを読み込む

sayChan := make(chan string) 
go func() {
prompt := username + “>”
bio := bufio.NewReader(os.Stdin)
for {
fmt.Print(prompt)
line, _, err := bio.ReadLine()
if err != nil {
fmt.Println(err)
sayChan <- “/exit”
return
}
sayChan <- string(line)
}
}()
conn.Do(“PUBLISH”, “messages”, userName+” has joined”)
for !chatExit { 
select {
case msg := <-subChan: 
fmt.Println(msg)
case <-tickerChan: 
val, err = conn.Do(“SET”, userKey, userName, “XX”, “EX”, “120”)
if err != nil || val == nil {
fmt.Println(“Heartbeat set failed”)
chatExit = true
}
case line := <-sayChan: 
if line == “/exit” {
chatExit = true
}
else if line == “/who” { 
names, _ := redis.Strings(conn.Do(“SMEMBERS”, “users”))
for _, name := range names {
fmt.Println(name)
}
}
else { 
conn.Do(“PUBLISH”, “messages”, username+”:”+line)
}

チャットからの退出

conn.Do(“DEL”, userkey) 
conn.Do(“SREM”, “users”, userName)
conn.Do(“PUBLISH”, “messages”, userName+” has left”)

まとめ

Eureka Engineering

Learn about Eureka’s engineering efforts, product developments and more.

Koya Suzuki

Written by

Web Developer at Eureka, Inc.

Eureka Engineering

Learn about Eureka’s engineering efforts, product developments and more.