我正在Windows上使用Redis编写一个简单的Go Web应用程序(首次尝试使用Redis)。我正在使用go-redis软件包连接到Redis。

package main

import (
    "fmt"
    "net/http"
    "text/template"

    "github.com/go-redis/redis"
    "github.com/gorilla/mux"
)

var client *redis.Client
var tmpl *template.Template

func init() {
    client = redis.NewClient(&redis.Options{
        Addr:     "localhost:6397",
        Password: "",
        DB:       0,
    })
    tmpl = template.Must(template.ParseGlob("./templates/*.gohtml"))
    pong, err := client.Ping().Result()
    fmt.Println(pong, err)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", indexHandler).Methods("GET")
    http.Handle("/", router)
    http.ListenAndServe(":1234", nil)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    comments, err := client.LRange("comments", 0, 10).Result()
    check(err)
    tmpl.ExecuteTemplate(w, "index.gohtml", comments)
}

func check(err error) {
    if err != nil {
        fmt.Println(err)
        return
    }
}
但是当我运行这段代码时,我得到了

我能找到的唯一答案是“启动redis服务器”。我的Redis服务器已启动并正在运行(通过在Redis客户端中使用“PING”命令进行检查)。我也尝试过以管理员身份运行它,但是没有运气。
截屏:

最佳答案

这很可能是由于Redis服务器在6379端口(这是Redis服务器的默认端口)上运行而引起的,但是您正在尝试连接到6397端口。

将服务器地址更改为:
Addr: "localhost:6379"
Addr: "localhost:6397"
那应该可以解决您的问题。

10-01 20:55
查看更多