1、Docker略过
2、Go语言操作Redis
//使用下面的命令启动一个名为 redis507 的 5.0.7 版本的 redis server环境。
//此处的版本、容器名和端口号可以根据自己需要设置。
$ docker run --name redis507 -p 6379:6379 -d redis:5.0.7
//启动一个 redis-cli 连接上面的 redis server。
$ docker run -it --network host --rm redis:5.0.7 redis-cli
//下载redis
$ go get github.com/go-redis/redis/v8
//config.yaml
redis:
addr: "localhost:6379"
pwd: ""
DB: 0
poolSize: 30
minIdleConn: 30
//初始化
RDS = redis.NewClient(&redis.Options{
Addr: viper.GetString("redis.addr"),
Password: viper.GetString("redis.pwd"),
DB: viper.GetInt("redis.DB"),
PoolSize: viper.GetInt("redis.poolSize"),
MinIdleConns: viper.GetInt("redis.minIdleConn"),
})
//发布订阅方法
const PublishKey = "websocket"
func Publish(ctx context.Context, channel string, msg string) error {
ZPrintln("publish message", msg)
return RDS.Publish(ctx, channel, msg).Err()
}
func Subscribe(ctx context.Context, channel string) (string, error) {
rs, err := RDS.Ping(ctx).Result()
if err != nil {
ZPrintln("ping err:", err)
return "", err
}
ZPrintln("ping result", rs)
sub := RDS.Subscribe(ctx, channel)
msg, err := sub.ReceiveMessage(ctx)
ZPrintln("receive message ", msg.Payload)
return msg.Payload, err
}
//userService.go
// 防止跨域站点伪造请求
var upGrade = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func SendMsg(ctx *gin.Context) {
utils.ZPrintln("send msg method called...")
conn, err := upGrade.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
utils.ZPrintln("websocket conn err:", err)
return
}
defer func(conn *websocket.Conn) {
err = conn.Close()
if err != nil {
utils.ZPrintln("websocket conn close err:", err)
}
}(conn)
MsgHandler(conn, ctx)
}
func MsgHandler(conn *websocket.Conn, ctx *gin.Context) {
utils.ZPrintln("msg handler method called...")
msg, err := utils.Subscribe(ctx, utils.PublishKey)
if err != nil {
utils.ZPrintln("subscribe err:", err)
return
}
date := time.Now().Format("2006-01-02 15:04:05")
mbody := fmt.Sprintf("[Message][%s]:%s", date, msg)
err = conn.WriteMessage(1, []byte(mbody))
if err != nil {
utils.ZPrintln("conn write message err:", err)
}
}
//router.go
func Router() *gin.Engine {
r := gin.Default()
docs.SwaggerInfo.BasePath = "/api/v1"
v1 := r.Group("api/v1")
{
v1.GET("index", service.GetIndex)
v1.GET("user/userList", service.GetUserList)
v1.GET("user/createUser", service.CreateUser)
v1.GET("user/deleteUser", service.DeleteUser)
v1.POST("user/updateUser", service.UpdateUser)
v1.POST("user/login", service.UserLogin)
v1.GET("user/sendMsg", service.SendMsg)
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
return r
}
测试