概述
如果您没有Golang的基础,应该学习如下前置课程。
- Golang零基础入门
- Golang面向对象编程
- Go Web 基础
- Go语言开发REST API接口_20240728
- Go语言操作MySQL开发用户管理系统API教程_20240729
- Redis零基础快速入门_20231227
基础不好的同学每节课的代码最好配合视频进行阅读和学习,如果基础比较扎实,则阅读本教程巩固一下相关知识点即可,遇到不会的知识点再看视频。
视频课程
最近发现越来越多的公司在用Golang了,所以精心整理了一套视频教程给大家,这个是其中的第6部,后续还会有很多。
视频已经录制完成,完整目录截图如下:
本套课程的特色是每节课都是一个核心知识点,每个视频控制在十分钟左右,精简不废话,拒绝浪费大家的时间。
课程目录
- 01 概述
- 02 建立Redis连接对象
- 03 edis的打开和关闭方法
- 04 通过Do执行get和set命令
- 05 通过String自动转换字符串
- 06 通过Do实现mset和mget的操作
- 07 通过Do实现hset和hget的操作
- 08 通过Do实现lpush和lpop以及llen的操作
- 09 Redis的连接池介绍
- 10 Redis连接池的创建和使用
- 11 Redis的管道操作
- 12 Redis的事务操作
- 13 实现redigo的本地化
- 14 对zdpgo_redis的包结构进行调整
- 15 发布zdpgo_redisv1.1.0版本
- 16 新增用户
- 17 修改用户
- 18 删除用户
- 19 查询所有用户
- 20 实现查询所有用户的接口并进行测试
- 21 实现新增用户的接口并进行测试
- 22 解决ID唯一性的问题
- 23 实现修改用户的接口并进行测试
- 24 实现删除用户的接口并进行测试
- 25 实现根据ID查询用户的接口并进行测试
- 26 总结
完整代码
01 概述
02 建立Redis连接对象
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)func main() {r, err := redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}defer r.Close()
}
03 edis的打开和关闭方法
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (r redis.Connerr error
)func InitRedis() {r, err = redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}
}func CloseRedis() {r.Close()
}func main() {InitRedis()defer CloseRedis()fmt.Println("主程序的操作。。。")
}
04 通过Do执行get和set命令
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (r redis.Connerr error
)func InitRedis() {r, err = redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}
}func CloseRedis() {r.Close()
}func main() {InitRedis()defer CloseRedis()// set 操作_, err = r.Do("SET", "name", "张三")if err != nil {fmt.Println(err)return}// get 操作var reply interface{}reply, err = r.Do("GET", "name")if err != nil {fmt.Println(err)return}fmt.Println(string(reply.([]byte)))
}
05 通过String自动转换字符串
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (r redis.Connerr error
)func InitRedis() {r, err = redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}
}func CloseRedis() {r.Close()
}func main() {InitRedis()defer CloseRedis()// set 操作_, err = r.Do("SET", "name", "张三")if err != nil {fmt.Println(err)return}// get 操作var reply stringreply, err = redis.String(r.Do("GET", "name"))if err != nil {fmt.Println(err)return}fmt.Println(reply)
}
06 通过Do实现mset和mget的操作
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (r redis.Connerr error
)func InitRedis() {r, err = redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}
}func CloseRedis() {r.Close()
}func main() {InitRedis()defer CloseRedis()// set 操作// 也一定要注意,是:key1,value1,key2,value2... 的格式_, err = r.Do("MSET", "name", "张三", "age", 22, "gender", "男")if err != nil {fmt.Println(err)return}// get 操作// 这个传递的是想要哪些keyvar reply []stringreply, err = redis.Strings(r.Do("MGET", "name", "age", "gender"))if err != nil {fmt.Println(err)return}fmt.Println(reply)
}
07 通过Do实现hset和hget的操作
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (r redis.Connerr error
)func InitRedis() {r, err = redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}
}func CloseRedis() {r.Close()
}func main() {InitRedis()defer CloseRedis()_, err = r.Do("HSET", "user", "name", "张三")if err != nil {fmt.Println(err)return}var reply stringreply, err = redis.String(r.Do("HGET", "user", "name"))if err != nil {fmt.Println(err)return}fmt.Println(reply)
}
08 通过Do实现lpush和lpop以及llen的操作
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (r redis.Connerr error
)func InitRedis() {r, err = redis.Dial("tcp", "127.0.0.1:6379")if err != nil {fmt.Println(err)return}
}func CloseRedis() {r.Close()
}func main() {InitRedis()defer CloseRedis()_, err = r.Do("LPUSH", "arr", "张三", "李四", "王五")if err != nil {fmt.Println(err)return}var reply stringreply, err = redis.String(r.Do("LPOP", "arr"))if err != nil {fmt.Println(err)return}fmt.Println(reply)var length intlength, err = redis.Int(r.Do("LLEN", "arr"))if err != nil {fmt.Println(err)return}fmt.Println(length)}
09 Redis的连接池介绍
10 Redis连接池的创建和使用
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (pool *redis.Poolerr error
)func InitRedis() {pool = &redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (redis.Conn, error) {return redis.Dial("tcp", "127.0.0.1:6379")},}
}func main() {InitRedis()r := pool.Get()defer r.Close()_, err = r.Do("LPUSH", "arr", "张三", "李四", "王五")if err != nil {fmt.Println(err)return}var reply stringreply, err = redis.String(r.Do("LPOP", "arr"))if err != nil {fmt.Println(err)return}fmt.Println(reply)var length intlength, err = redis.Int(r.Do("LLEN", "arr"))if err != nil {fmt.Println(err)return}fmt.Println(length)}
11 Redis的管道操作
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (pool *redis.Poolerr error
)func InitRedis() {pool = &redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (redis.Conn, error) {return redis.Dial("tcp", "127.0.0.1:6379")},}
}func main() {InitRedis()r := pool.Get()defer r.Close()// 写入缓冲r.Send("SET", "name1", "张三")r.Send("SET", "name2", "李四")// 清空缓冲,写入服务端(Redis)r.Flush()// 读取:先进先出receive, err := r.Receive()fmt.Printf("receive:%#v, err:%v\n", receive, err)receive, err = r.Receive()fmt.Printf("receive:%#v, err:%v\n", receive, err)// 因为没有数据了,所以会一直处于等待状态receive, err = r.Receive()fmt.Printf("receive:%#v, err:%v\n", receive, err)
}
12 Redis的事务操作
package mainimport ("fmt""github.com/gomodule/redigo/redis"
)var (pool *redis.Poolerr error
)func InitRedis() {pool = &redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (redis.Conn, error) {return redis.Dial("tcp", "127.0.0.1:6379")},}
}func main() {InitRedis()r := pool.Get()defer r.Close()r.Send("MULTI") // 开启事务// 事务过程中的一些业务操作r.Send("INCR", "num1")r.Send("INCR", "num2")reply, err := r.Do("EXEC") // 执行事务fmt.Printf("%#v err:%v\n", reply, err)
}
13 实现redigo的本地化
14 对zdpgo_redis的包结构进行调整
15 发布zdpgo_redisv1.1.0版本
16 新增用户
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_redis"
)var (pool *zdpgo_redis.Poolerr error
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}type User struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`
}func main() {InitRedis()r := pool.Get()defer r.Close()// string hash list// string hash users:{1:{id:1,xxx},2:xxx}// string 代码会更简单zs := User{2, "李四", 23}key := fmt.Sprintf("user/%d", zs.Id)zsBytes, _ := json.Marshal(zs)value := string(zsBytes)r.Do("SET", key, value)value2, _ := zdpgo_redis.String(r.Do("GET", key))fmt.Println(value2)
}
17 修改用户
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_redis"
)var (pool *zdpgo_redis.Poolerr error
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}type User struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`
}func main() {InitRedis()r := pool.Get()defer r.Close()id := 1name := "李四"// 查询key := fmt.Sprintf("user/%d", id)value2, _ := zdpgo_redis.String(r.Do("GET", key))fmt.Println(value2)// 解析var user Userjson.Unmarshal([]byte(value2), &user)fmt.Println(user)// 修改user.Name = name// 重新存储jsonBytes, _ := json.Marshal(user)fmt.Println(string(jsonBytes))r.Do("SET", key, string(jsonBytes))
}
18 删除用户
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_redis"
)var (pool *zdpgo_redis.Poolerr error
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}type User struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`
}func main() {InitRedis()r := pool.Get()defer r.Close()id := 1// 查询key := fmt.Sprintf("user/%d", id)value2, _ := zdpgo_redis.String(r.Do("GET", key))fmt.Println(value2)// 删除r.Do("DEL", key)// 再查询value2, _ = zdpgo_redis.String(r.Do("GET", key))fmt.Println(value2)
}
19 查询所有用户
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_redis"
)var (pool *zdpgo_redis.Poolerr error
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}type User struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`
}func main() {InitRedis()r := pool.Get()defer r.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(r.Do("KEYS", "user/*"))fmt.Println(userKeys)// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(r.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}fmt.Println(users)
}
20 实现查询所有用户的接口并进行测试
package mainimport ("encoding/json""github.com/zhangdapeng520/zdpgo_httprouter""github.com/zhangdapeng520/zdpgo_redis""net/http""time"
)type User struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`
}var (pool *zdpgo_redis.Pool
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}func RouterGetUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(rdb.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}zdpgo_httprouter.ResponseSuccess(w, users)
}func main() {InitRedis()router := zdpgo_httprouter.New()router.GET("/user", RouterGetUser)server := &http.Server{Addr: "0.0.0.0:8888",Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""io""net/http"
)func main() {resp, err := http.Get("http://localhost:8888/user")if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}
21 实现新增用户的接口并进行测试
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""github.com/zhangdapeng520/zdpgo_redis""net/http""time"
)type User struct {Id int `json:"id"`Name string `json:"name"`Age int `json:"age"`
}var (pool *zdpgo_redis.Pool
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}func RouterGetUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(rdb.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}zdpgo_httprouter.ResponseSuccess(w, users)
}func RouterAddUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Userzdpgo_httprouter.GetJson(r, &user)id := time.Now().Nanosecond()user.Id = id// 新增key := fmt.Sprintf("user/%d", user.Id)zsBytes, _ := json.Marshal(user)value := string(zsBytes)rdb.Do("SET", key, value)// 返回zdpgo_httprouter.ResponseSuccess(w, user)
}func main() {InitRedis()router := zdpgo_httprouter.New()router.POST("/user", RouterAddUser)router.GET("/user", RouterGetUser)server := &http.Server{Addr: "0.0.0.0:8888",Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/user"data := map[string]interface{}{"name": "王五","age": 35,}resp, err := zdpgo_httprouter.SendJson("POST", targetUrl, data)if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}
22 解决ID唯一性的问题
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""github.com/zhangdapeng520/zdpgo_redis""net/http""time"
)type User struct {Id int64 `json:"id"`Name string `json:"name"`Age int `json:"age"`
}var (pool *zdpgo_redis.Pool
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}func RouterGetUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(rdb.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}zdpgo_httprouter.ResponseSuccess(w, users)
}func RouterAddUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Userzdpgo_httprouter.GetJson(r, &user)id := time.Now().UnixNano()user.Id = id// 新增key := fmt.Sprintf("user/%d", user.Id)zsBytes, _ := json.Marshal(user)value := string(zsBytes)rdb.Do("SET", key, value)// 返回zdpgo_httprouter.ResponseSuccess(w, user)
}func main() {InitRedis()router := zdpgo_httprouter.New()router.POST("/user", RouterAddUser)router.GET("/user", RouterGetUser)server := &http.Server{Addr: "0.0.0.0:8888",Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/user"data := map[string]interface{}{"name": "王五","age": 35,}resp, err := zdpgo_httprouter.SendJson("POST", targetUrl, data)if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}
23 实现修改用户的接口并进行测试
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""github.com/zhangdapeng520/zdpgo_redis""net/http""time"
)type User struct {Id int64 `json:"id"`Name string `json:"name"`Age int `json:"age"`
}var (pool *zdpgo_redis.Pool
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}func RouterGetUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(rdb.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}zdpgo_httprouter.ResponseSuccess(w, users)
}func RouterAddUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Userzdpgo_httprouter.GetJson(r, &user)id := time.Now().UnixNano()user.Id = id// 新增key := fmt.Sprintf("user/%d", user.Id)zsBytes, _ := json.Marshal(user)value := string(zsBytes)rdb.Do("SET", key, value)// 返回zdpgo_httprouter.ResponseSuccess(w, user)
}func RouterUpdateUser(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Uservar idStr = ps.ByName("id")zdpgo_httprouter.GetJson(r, &user)// 查询key := fmt.Sprintf("user/%s", idStr)userJson, _ := zdpgo_redis.String(rdb.Do("GET", key))// 解析var dbUser Userjson.Unmarshal([]byte(userJson), &dbUser)// 修改dbUser.Name = user.NamedbUser.Age = user.Age// 重新存储jsonBytes, _ := json.Marshal(dbUser)rdb.Do("SET", key, string(jsonBytes))// 返回zdpgo_httprouter.ResponseSuccess(w, dbUser)
}func main() {InitRedis()router := zdpgo_httprouter.New()router.POST("/user", RouterAddUser)router.GET("/user", RouterGetUser)router.PUT("/user/:id", RouterUpdateUser)server := &http.Server{Addr: "0.0.0.0:8888",Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/user/108534300"data := map[string]interface{}{"name": "王六","age": 35,}resp, err := zdpgo_httprouter.SendJson("PUT", targetUrl, data)if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}
24 实现删除用户的接口并进行测试
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""github.com/zhangdapeng520/zdpgo_redis""net/http""time"
)type User struct {Id int64 `json:"id"`Name string `json:"name"`Age int `json:"age"`
}var (pool *zdpgo_redis.Pool
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}func RouterGetUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(rdb.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}zdpgo_httprouter.ResponseSuccess(w, users)
}func RouterAddUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Userzdpgo_httprouter.GetJson(r, &user)id := time.Now().UnixNano()user.Id = id// 新增key := fmt.Sprintf("user/%d", user.Id)zsBytes, _ := json.Marshal(user)value := string(zsBytes)rdb.Do("SET", key, value)// 返回zdpgo_httprouter.ResponseSuccess(w, user)
}func RouterUpdateUser(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Uservar idStr = ps.ByName("id")zdpgo_httprouter.GetJson(r, &user)// 查询key := fmt.Sprintf("user/%s", idStr)userJson, _ := zdpgo_redis.String(rdb.Do("GET", key))// 解析var dbUser Userjson.Unmarshal([]byte(userJson), &dbUser)// 修改dbUser.Name = user.NamedbUser.Age = user.Age// 重新存储jsonBytes, _ := json.Marshal(dbUser)rdb.Do("SET", key, string(jsonBytes))// 返回zdpgo_httprouter.ResponseSuccess(w, dbUser)
}func RouterDeleteUser(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var idStr = ps.ByName("id")// 查询key := fmt.Sprintf("user/%s", idStr)rdb.Do("DEL", key)// 返回zdpgo_httprouter.ResponseSuccess(w, nil)
}func main() {InitRedis()router := zdpgo_httprouter.New()router.POST("/user", RouterAddUser)router.GET("/user", RouterGetUser)router.PUT("/user/:id", RouterUpdateUser)router.DELETE("/user/:id", RouterDeleteUser)server := &http.Server{Addr: "0.0.0.0:8888",Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/user/53"data := map[string]interface{}{}resp, err := zdpgo_httprouter.SendJson("DELETE", targetUrl, data)if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}
25 实现根据ID查询用户的接口并进行测试
package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""github.com/zhangdapeng520/zdpgo_redis""net/http""time"
)type User struct {Id int64 `json:"id"`Name string `json:"name"`Age int `json:"age"`
}var (pool *zdpgo_redis.Pool
)func InitRedis() {pool = &zdpgo_redis.Pool{MaxIdle: 16,MaxActive: 1024,IdleTimeout: 300,Dial: func() (zdpgo_redis.Conn, error) {return zdpgo_redis.Dial("tcp", "127.0.0.1:6379")},}
}func RouterGetUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()// 获取所有的keyuserKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))// 查询var users []Userfor _, key := range userKeys {var user UseruserStr, _ := zdpgo_redis.String(rdb.Do("GET", key))json.Unmarshal([]byte(userStr), &user)users = append(users, user)}zdpgo_httprouter.ResponseSuccess(w, users)
}func RouterAddUser(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Userzdpgo_httprouter.GetJson(r, &user)id := time.Now().UnixNano()user.Id = id// 新增key := fmt.Sprintf("user/%d", user.Id)zsBytes, _ := json.Marshal(user)value := string(zsBytes)rdb.Do("SET", key, value)// 返回zdpgo_httprouter.ResponseSuccess(w, user)
}func RouterUpdateUser(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var user Uservar idStr = ps.ByName("id")zdpgo_httprouter.GetJson(r, &user)// 查询key := fmt.Sprintf("user/%s", idStr)userJson, _ := zdpgo_redis.String(rdb.Do("GET", key))// 解析var dbUser Userjson.Unmarshal([]byte(userJson), &dbUser)// 修改dbUser.Name = user.NamedbUser.Age = user.Age// 重新存储jsonBytes, _ := json.Marshal(dbUser)rdb.Do("SET", key, string(jsonBytes))// 返回zdpgo_httprouter.ResponseSuccess(w, dbUser)
}func RouterDeleteUser(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var idStr = ps.ByName("id")// 查询key := fmt.Sprintf("user/%s", idStr)rdb.Do("DEL", key)// 返回zdpgo_httprouter.ResponseSuccess(w, nil)
}func RouterGetUserId(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {rdb := pool.Get()defer rdb.Close()var idStr = ps.ByName("id")// 查询key := fmt.Sprintf("user/%s", idStr)userJson, _ := zdpgo_redis.String(rdb.Do("GET", key))var dbUser Userjson.Unmarshal([]byte(userJson), &dbUser)// 返回zdpgo_httprouter.ResponseSuccess(w, dbUser)
}func main() {InitRedis()router := zdpgo_httprouter.New()router.POST("/user", RouterAddUser)router.GET("/user", RouterGetUser)router.PUT("/user/:id", RouterUpdateUser)router.DELETE("/user/:id", RouterDeleteUser)router.GET("/user/:id", RouterGetUserId)server := &http.Server{Addr: "0.0.0.0:8888",Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""io""net/http"
)func main() {resp, err := http.Get("http://localhost:8888/user/1")if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}
总结
本套教程主要讲解Go语言操作Redis基础知识,然后还讲解了管道,连接池,事务等高级用户。借助用户管理这个业务为中心,详细讲解了如何使用Go语言加Redis实现用户的增删改查操作,之后有结合httprouter的用法,开发用户管理的增删改查API接口。
通过本套课程,能帮你入门Go语言操作Redis的技术。
如果您需要完整的源码,打赏20元即可。
人生苦短,我用Python,我是您身边的Python私教~