LoginSignup
3
2

More than 5 years have passed since last update.

heroku上のGoでRedis To Goを使う

Posted at

はじめに

今回の内容は、heroku上でGoを実行する際にアドオンのRedisを使う方法の説明になります。

ちなみにheroku上でGoを動かす説明は、こちらなどが参考になるかと思います。

herokuの環境変数

REDISTOGO_URLです。

この環境変数から取得できる値は以下のような内容になります。

redis://redistogo:<password>@xxxxxx.redistogo.com:11068/

手順

今回Redisのアクセスに以下のライブラリを使います。

環境変数から取得した内容をredis.Optionsに詰め替える必要があるため以下のようになります。

redis.go
package example

import (
    "fmt"
    "net/url"
    "os"

    "gopkg.in/redis.v2"
)

func redisExample() {
    addr, password := getHerokuRedisAddr()
    client := redis.NewTCPClient(&redis.Options{
        Addr: addr,
        Password: password,
    })
    defer client.Close()

    // redisへアクセス(適当なコード)
    fmt.Println(client.Get("hoge").Result())
}

// local実行用に環境変数がないときは`localhost:6379`を返します
func getHerokuRedisAddr() (addr string, password string) {
    addr = "localhost:6379"
    password = ""

    redisURL := os.Getenv("REDISTOGO_URL")
    if redisURL == "" {
        return
    }

    redisInfo, err := url.Parse(redisURL)
    if err != nil {
        return
    }

    addr = redisInfo.Host
    if redisInfo.User != nil {
        password, _ = redisInfo.User.Password()
    }
    return
}

一応、ローカル環境でも動くようにしています。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2