⚡ 第21课:缓存Redis

Web开发 第3阶段·第7/7课

📋 本课目标

🔬 代码演示与验证

package main
import ("encoding/json";"fmt";"sync";"time")
type CacheItem struct{Value interface{};ExpiresAt time.Time}
func(c *CacheItem)IsExpired()bool{return !c.ExpiresAt.IsZero()&&time.Now().After(c.ExpiresAt)}
type Cache struct{data map[string]*CacheItem;mu sync.RWMutex}
func NewCache()*Cache{c:=&Cache{data:make(map[string]*CacheItem)};go c.cleanup();return c}
func(c *Cache)Set(k string,v interface{},ttl time.Duration){c.mu.Lock();defer c.mu.Unlock();i:=&CacheItem{Value:v};if ttl>0{i.ExpiresAt=time.Now().Add(ttl)};c.data[k]=i}
func(c *Cache)Get(k string)(interface{},bool){c.mu.RLock();defer c.mu.RUnlock();i,ok:=c.data[k];if !ok||i.IsExpired(){return nil,false};return i.Value,true}
func(c *Cache)Incr(k string)int{c.mu.Lock();defer c.mu.Unlock();i,ok:=c.data[k];if !ok||i.IsExpired(){c.data[k]=&CacheItem{Value:1};return 1};if n,ok:=i.Value.(int);ok{i.Value=n+1;return n+1};return 0}
func(c *Cache)cleanup(){for range time.NewTicker(time.Second).C{c.mu.Lock();for k,v:=range c.data{if v.IsExpired(){delete(c.data,k)}};c.mu.Unlock()}}
func main() {
    cache:=NewCache()
    cache.Set("user:1",map[string]string{"name":"张三"},10*time.Minute)
    cache.Set("counter",0,0)
    if v,ok:=cache.Get("user:1");ok{b,_:=json.Marshal(v);fmt.Printf("user:1=%s\n",b)}
    for i:=0;i<5;i++{fmt.Printf("counter=%d\n",cache.Incr("counter"))}
    cache.Set("temp","过期测试",500*time.Millisecond)
    if _,ok:=cache.Get("temp");ok{fmt.Println("temp存在")}
    time.Sleep(600*time.Millisecond)
    if _,ok:=cache.Get("temp");!ok{fmt.Println("temp已过期")}
    fmt.Println("\n=== Redis数据结构 ===")
    fmt.Println("String/Hash/List/Set/ZSet")
    fmt.Println("\n=== 缓存模式 ===")
    fmt.Println("Cache-Aside/Read-Through/Write-Through/Write-Behind")
}

🔍 运行验证

✅ 验证通过 — 实机运行结果:

user:1={"name":"张三"}
counter=1
counter=2
counter=3
counter=4
counter=5
temp存在
temp已过期

=== Redis数据结构 ===
String/Hash/List/Set/ZSet

=== 缓存模式 ===
Cache-Aside/Read-Through/Write-Through/Write-Behind

🧠 Redis

Redis: 内存KV数据库 数据结构: String/Hash/List/Set/ZSet 缓存模式: Cache-Aside/Read/Write-Through

缓存模式

🔑 本课要点回顾

知识点关键内容
RedisSet/Get/Delete/Incr
TTL过期策略
数据结构String/Hash/List/Set/ZSet
缓存模式Cache-Aside/Read-Through

🏋️ 练习

分布式锁

Redis+过期+续期

排行榜

ZSet实现

会话缓存

Session存储

🏆

成就解锁:缓存专家!🎉 Web开发完成!

📖 延伸阅读

🎯 实战建议

  1. 动手编写代码,不要只看不练
  2. 使用go doc查看标准库文档
  3. 编写测试用例验证理解
  4. 阅读优秀开源项目的源码
  5. 在项目中应用所学知识

⚡ 性能提示

// 1. 预分配切片容量
s := make([]int, 0, expectedSize)

// 2. 使用strings.Builder拼接
var b strings.Builder
b.WriteString("hello")

// 3. 对象池复用
var bufPool = sync.Pool{New: func() interface{} { return new(bytes.Buffer) }}

// 4. 减少逃逸分析
// 小对象栈分配,大对象堆分配

// 5. benchmark测试
func BenchmarkXxx(b *testing.B) {
    for i := 0; i < b.N; i++ { ... }
}

🔍 调试技巧

// 1. fmt.Printf格式化
fmt.Printf("%+v
", struct)  // 带字段名
fmt.Printf("%#v
", value)   // Go语法

// 2. log包
log.Printf("debug: value=%v", val)

// 3. delve调试器
// dlv debug ./main.go

// 4. pprof性能分析
import _ "net/http/pprof"
go http.ListenAndServe(":6060", nil)

📖 延伸阅读与资源

🎯 实战开发建议

  1. 动手编码 — 只看不练等于没学,每课代码必须自己敲一遍
  2. 使用go docgo doc fmt.Printf 查看标准库文档
  3. 编写测试go test 验证你的理解是否正确
  4. 阅读源码 — 标准库是Go最佳实践的活教材
  5. 项目实战 — 在真实项目中应用所学

⚡ Go性能优化清单

// 1. 预分配切片容量 — 避免频繁扩容
s := make([]int, 0, expectedSize)

// 2. strings.Builder拼接 — 比fmt.Sprintf快3-5倍
var b strings.Builder
b.WriteString("hello")
b.WriteString(" world")
result := b.String()

// 3. sync.Pool对象复用 — 减少GC压力
var bufPool = sync.Pool{
    New: func() interface{} { return new(bytes.Buffer) },
}
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)

// 4. 减少堆分配 — 小对象栈分配,避免逃逸
// 用 go build -gcflags="-m" 分析逃逸

// 5. 使用benchmark验证性能
func BenchmarkXxx(b *testing.B) {
    for i := 0; i < b.N; i++ {
        // 被测代码
    }
}
// go test -bench=. -benchmem

🔍 调试与排查技巧

// 1. 格式化调试输出
fmt.Printf("%+v
", myStruct)  // 带字段名
fmt.Printf("%#v
", myValue)   // Go语法表示

// 2. log包运行时日志
log.Printf("[DEBUG] value=%v", val)
log.SetFlags(log.LstdFlags | log.Lshortfile)

// 3. delve源码调试器
// 安装: go install github.com/go-delve/delve/cmd/dlv@latest
// 使用: dlv debug ./main.go
// 命令: break main.main / continue / next / print

// 4. pprof性能分析
import _ "net/http/pprof"
go http.ListenAndServe(":6060", nil)
// 访问: http://localhost:6060/debug/pprof/
// 命令: go tool pprof http://localhost:6060/debug/pprof/profile

// 5. race detector竞态检测
// go run -race main.go
// go test -race ./...

📊 Go工具生态

工具用途安装
golangci-lint代码静态检查go install github.com/golangci/golangci-lint/cmd/...@latest
gofumpt代码格式化(增强)go install mvdan.cc/gofumpt@latest
goimports自动管理importgo install golang.org/x/tools/cmd/goimports@latest
dlv源码调试器go install github.com/go-delve/delve/cmd/dlv@latest
air热重载开发go install github.com/cosmtrek/air@latest
swagSwagger文档生成go install github.com/swaggo/swag/cmd/swag@latest
migrate数据库迁移go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest

🏗️ Go项目结构最佳实践

myproject/
├── cmd/                    # 可执行程序入口
│   └── server/
│       └── main.go
├── internal/               # 私有代码(不可外部导入)
│   ├── handler/            # HTTP处理
│   ├── service/            # 业务逻辑
│   ├── repository/         # 数据访问
│   └── model/              # 数据模型
├── pkg/                    # 可复用公共包
│   └── utils/
├── api/                    # API定义(proto/openapi)
├── configs/                # 配置文件
├── scripts/                # 构建/部署脚本
├── test/                   # 集成测试
├── go.mod
├── go.sum
├── Makefile
└── Dockerfile

🌐 Go Web开发生态

类别推荐方案替代方案
Web框架GinEcho / Chi / Fiber
ORMGORMEnt / sqlx / sqlc
配置Viperkoanf
日志zapzerolog / slog
验证validatorgo-playground/validator
缓存go-redisredigo
JWTgolang-jwt
Swaggerswag
测试testify
Mockgomocktestify/mock

💡 编码规范

// 命名规范
// 包名: 小写单词, 不用下划线  package httputil
// 导出: 大写开头              func CreateUser()
// 未导出: 小写开头            func validateInput()
// 接口: -er后缀              type Reader interface{}
// 常量: 驼峰                 const maxRetries = 3
// 枚举: 类型+常量            type Role int; const Admin Role = 0

// 错误处理规范
// 错误变量: Err前缀           var ErrNotFound = errors.New("...")
// 错误类型: Error后缀         type ValidationError struct{...}
// 包装: %w                    fmt.Errorf("查询失败: %w", err)

// 注释规范
// 导出符号必须有注释
// 注释以符号名开头            // CreateUser creates a new user.
// 包注释: doc.go              // Package user handles user operations.

🔐 安全编码要点

// 1. 输入验证 — 永远不信任用户输入
// 2. SQL注入 — 使用参数化查询
db.Query("SELECT * FROM users WHERE id = $1", id)  // ✅
db.Query("SELECT * FROM users WHERE id = " + id)    // ❌

// 3. XSS防护 — HTML转义
template.HTML(escape(userInput))  // 或使用html/template自动转义

// 4. CSRF — 使用token验证
// 5. 密码 — bcrypt/argon2哈希, 永不明文存储
hashed, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)

// 6. HTTPS — 生产环境必须
// 7. 日志脱敏 — 不记录密码/Token
log.Printf("user login: id=%d", userID)  // ✅
log.Printf("password=%s", pwd)            // ❌

📦 依赖管理规范

// go.mod最佳实践
module github.com/yourorg/yourproject

go 1.22

// 直接依赖 — 项目直接使用的包
require (
    github.com/gin-gonic/gin v1.9.1
    gorm.io/gorm v1.25.0
)

// 间接依赖 — 自动管理, 不要手动编辑
require (
    github.com/json-iterator/go v1.1.12 // indirect
)

// 替换 — 本地开发/ fork修复
replace github.com/original/pkg => ../local-fork

// 排除 — 排除有问题的版本
exclude github.com/broken/pkg v1.0.0