goframe redis示例

package main

import (
	"time"

	_ "github.com/gogf/gf/contrib/nosql/redis/v2" // !!! important
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gsession"
	"github.com/gogf/gf/v2/os/gtime"
)

func main() {
    // 创建一个服务器实例
	s := g.Server()
    // 设置会话的最大生命周期为1分钟
	s.SetSessionMaxAge(time.Minute)
    // 设置会话存储方式为Redis,使用g.Redis()获取Redis实例
	s.SetSessionStorage(gsession.NewStorageRedis(g.Redis()))
    // 创建一个路由组,用于分组管理路由
	s.Group("/", func(group *ghttp.RouterGroup) {
        // 处理所有HTTP方法的"/set"请求
		group.ALL("/set", func(r *ghttp.Request) {
            // 将当前时间戳存储到会话中,键为"time"
			r.Session.Set("time", gtime.Timestamp())
            // 返回响应"ok"
			r.Response.Write("ok")
		})
        // 处理所有HTTP方法的"/get"请求
		group.ALL("/get", func(r *ghttp.Request) {
            // 返回会话中的所有数据
			r.Response.Write(r.Session.Data())
		})
        // 处理所有HTTP方法的"/del"请求
		group.ALL("/del", func(r *ghttp.Request) {
            // 移除会话中的所有数据
			_ = r.Session.RemoveAll()
            // 返回响应"ok"
			r.Response.Write("ok")
		})
	})
    // 设置服务器监听的端口号为8199
	s.SetPort(8199)
    // 启动服务器
	s.Run()
}

config/config.yaml:

redis:
  # 默认Redis配置组
  default:
    address: "127.0.0.1:6379"  # Redis服务器地址,格式: host:port
    db: 0                      # 数据库号,默认0
    pass: ""                   # 密码,无密码留空
    max_idle: 10               # 最大空闲连接数
    max_active: 100            # 最大活跃连接数
    idle_timeout: "60s"        # 空闲连接超时时间,默认60秒
    connect_timeout: "1s"      # 连接超时时间,默认1秒
    max_conn_lifetime: "300s"  # 连接最大存活时间,默认300秒

  # 其他自定义配置组(如cache)
  cache:
    address: "192.168.1.100:6379"
    db: 1
    pass: "your_secure_password"
    max_idle: 20
    max_active: 200
    idle_timeout: "30s"
    connect_timeout: "500ms"
posted @   卓能文  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示