我正在 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
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行这段代码时,我得到
dial tcp [::1]:6397: connectex: 无法建立连接,因为目标机器主动拒绝。
我能找到的唯一答案是“启动redis服务器”。我的 Redis 服务器已启动并正在运行(通过在 Redis 客户端中使用“PING”命令进行检查)。我也尝试过以管理员身份运行它,但没有成功。
截屏:

发生这种情况很可能是因为 Redis 服务器正在端口6379(即 Redis 服务器的默认端口)上运行,但您正在尝试连接到该端口6397。
将服务器地址更改为:
Addr: "localhost:6379"
从
Addr: "localhost:6397"
这应该可以解决你的问题。