Go+Redis零基础到用户管理系统API实战_20240730 课程笔记

概述

如果您没有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连接对象

go 复制代码
package main

import (
	"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的打开和关闭方法

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	r   redis.Conn
	err 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命令

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	r   redis.Conn
	err 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自动转换字符串

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	r   redis.Conn
	err 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 string
	reply, err = redis.String(r.Do("GET", "name"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)
}

06 通过Do实现mset和mget的操作

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	r   redis.Conn
	err 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 操作
	// 这个传递的是想要哪些key
	var reply []string
	reply, err = redis.Strings(r.Do("MGET", "name", "age", "gender"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)
}

07 通过Do实现hset和hget的操作

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	r   redis.Conn
	err 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 string
	reply, err = redis.String(r.Do("HGET", "user", "name"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)
}

08 通过Do实现lpush和lpop以及llen的操作

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	r   redis.Conn
	err 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 string
	reply, err = redis.String(r.Do("LPOP", "arr"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)

	var length int
	length, err = redis.Int(r.Do("LLEN", "arr"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(length)

}

09 Redis的连接池介绍

10 Redis连接池的创建和使用

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	pool *redis.Pool
	err  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 string
	reply, err = redis.String(r.Do("LPOP", "arr"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)

	var length int
	length, err = redis.Int(r.Do("LLEN", "arr"))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(length)

}

11 Redis的管道操作

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	pool *redis.Pool
	err  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的事务操作

go 复制代码
package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

var (
	pool *redis.Pool
	err  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 新增用户

go 复制代码
package main

import (
	"encoding/json"
	"fmt"
	"github.com/zhangdapeng520/zdpgo_redis"
)

var (
	pool *zdpgo_redis.Pool
	err  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 修改用户

go 复制代码
package main

import (
	"encoding/json"
	"fmt"
	"github.com/zhangdapeng520/zdpgo_redis"
)

var (
	pool *zdpgo_redis.Pool
	err  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
	name := "李四"

	// 查询
	key := fmt.Sprintf("user/%d", id)
	value2, _ := zdpgo_redis.String(r.Do("GET", key))
	fmt.Println(value2)

	// 解析
	var user User
	json.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 删除用户

go 复制代码
package main

import (
	"fmt"
	"github.com/zhangdapeng520/zdpgo_redis"
)

var (
	pool *zdpgo_redis.Pool
	err  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 查询所有用户

go 复制代码
package main

import (
	"encoding/json"
	"fmt"
	"github.com/zhangdapeng520/zdpgo_redis"
)

var (
	pool *zdpgo_redis.Pool
	err  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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(r.Do("KEYS", "user/*"))
	fmt.Println(userKeys)

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := zdpgo_redis.String(r.Do("GET", key))
		json.Unmarshal([]byte(userStr), &user)
		users = append(users, user)
	}
	fmt.Println(users)
}

20 实现查询所有用户的接口并进行测试

go 复制代码
package main

import (
	"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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := 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()
}
go 复制代码
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	resp, err := http.Get("http://localhost:8888/user")
	if err != nil {
		fmt.Println(err)
		return
	}

	body := resp.Body
	bodyBytes, err := io.ReadAll(body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(bodyBytes))
}

21 实现新增用户的接口并进行测试

go 复制代码
package main

import (
	"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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := 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 User
	zdpgo_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()
}
go 复制代码
package main

import (
	"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.Body
	bodyBytes, err := io.ReadAll(body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(bodyBytes))
}

22 解决ID唯一性的问题

go 复制代码
package main

import (
	"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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := 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 User
	zdpgo_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()
}
go 复制代码
package main

import (
	"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.Body
	bodyBytes, err := io.ReadAll(body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(bodyBytes))
}

23 实现修改用户的接口并进行测试

go 复制代码
package main

import (
	"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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := 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 User
	zdpgo_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 User
	var 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 User
	json.Unmarshal([]byte(userJson), &dbUser)

	// 修改
	dbUser.Name = user.Name
	dbUser.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()
}
go 复制代码
package main

import (
	"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.Body
	bodyBytes, err := io.ReadAll(body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(bodyBytes))
}

24 实现删除用户的接口并进行测试

go 复制代码
package main

import (
	"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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := 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 User
	zdpgo_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 User
	var 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 User
	json.Unmarshal([]byte(userJson), &dbUser)

	// 修改
	dbUser.Name = user.Name
	dbUser.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()
}
go 复制代码
package main

import (
	"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.Body
	bodyBytes, err := io.ReadAll(body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(bodyBytes))
}

25 实现根据ID查询用户的接口并进行测试

go 复制代码
package main

import (
	"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()

	// 获取所有的key
	userKeys, _ := zdpgo_redis.Strings(rdb.Do("KEYS", "user/*"))

	// 查询
	var users []User
	for _, key := range userKeys {
		var user User
		userStr, _ := 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 User
	zdpgo_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 User
	var 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 User
	json.Unmarshal([]byte(userJson), &dbUser)

	// 修改
	dbUser.Name = user.Name
	dbUser.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 User
	json.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()
}
go 复制代码
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	resp, err := http.Get("http://localhost:8888/user/1")
	if err != nil {
		fmt.Println(err)
		return
	}

	body := resp.Body
	bodyBytes, 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私教~

相关推荐
吉大一菜鸡2 小时前
FPGA学习(基于小梅哥Xilinx FPGA)学习笔记
笔记·学习·fpga开发
007php0074 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
CCSBRIDGE4 小时前
Magento2项目部署笔记
笔记
亦枫Leonlew5 小时前
微积分复习笔记 Calculus Volume 2 - 5.1 Sequences
笔记·数学·微积分
爱码小白6 小时前
网络编程(王铭东老师)笔记
服务器·网络·笔记
LuH11246 小时前
【论文阅读笔记】Learning to sample
论文阅读·笔记·图形渲染·点云
一棵开花的树,枝芽无限靠近你8 小时前
【PPTist】组件结构设计、主题切换
前端·笔记·学习·编辑器
犬余8 小时前
设计模式之桥接模式:抽象与实现之间的分离艺术
笔记·学习·设计模式·桥接模式
DT辰白8 小时前
基于Redis的网关鉴权方案与性能优化
数据库·redis·缓存
数据爬坡ing9 小时前
小白考研历程:跌跌撞撞,起起伏伏,五个月备战历程!!!
大数据·笔记·考研·数据分析