
安装依赖和环境变量
将数据库连接中的值替换为您的值。
#env file redis_address=localhost redis_port=6379 redis_password=123456 redis_db=0 #install on go go get github.com/redis/go-redis/v9
redis管理器
创建一个文件来管理.go 这将包含一个方法来获取与redis的连接,例如在其他模块和服务中。
人人站CMS是全新内核且开源免费的PHP企业网站开发建设管理系统,是一套高效、简洁、 强悍的PHP CMS源码,能够满足各类企业网站开发建设的需要。系统采用简单的模板标签,只要懂HTML就可快速开发企业网站。官方提供了大量网站模板免费下载和使用,将致力于为广大站长和企业提供简单易用的网站开发建设解决方案。模板特点: 1、安装即用,自带人人站CMS内核及企业站展示功能(产品,新闻,案例展示等),并可
package main
import (
"fmt"
"github.com/redis/go-redis/v9"
"os"
"strconv"
)
const customerdb = 0
type redismanager struct {
db int
client *redis.client
}
func newredisclient(customerdb int) (*redismanager, error) {
address := os.getenv("redis_address")
if address == "" {
return nil, fmt.errorf("redis_address is not set")
}
password := os.getenv("redis_password")
if password == "" {
return nil, fmt.errorf("redis_password is not set")
}
port := os.getenv("redis_port")
if port == " " {
return nil, fmt.errorf("redis_port is not set")
}
db := os.getenv("redis_db")
if db == "" {
return nil, fmt.errorf("redis_db is not set")
}
redisdb, err := strconv.atoi(db)
if err != nil {
return nil, fmt.errorf("redis_db is not a number")
}
cli := redis.newclient(&redis.options{
addr: fmt.sprintf("%s:%s", address, port),
password: password,
db: redisdb,
})
return &redismanager{
client: cli,
db: customerdb,
}, nil
}
func (rd *redismanager) setdb(db int) {
rd.db = db
}
创建用于管理实体(客户)存储库的结构
创建一个结构体来管理redis连接并获取与redis实体交互的所有方法(crud操作和查询)
有了这个结构,任何时候我们需要访问实体(客户)数据,我们都可以实例化并开始将其用作存储库模式。
type customerrepo struct {
cli *redismanager
db int
}
func newcustomerrepo() (*customerrepo, error) {
cli, err := newredisclient(customerdb)
if err != nil {
return nil, err
}
return &customerrepo{
cli: cli,
}, nil
}
创建结构体实体
在客户实体上添加与面包字段映射的标签。
redis:“-”与要保存在redis上的字段解除关系。如果您想要一个文件或结构不保存,请不要添加标签。
type customer struct {
id string `redis:"id"`
name string `redis:"name"`
email string `redis:"email"`
phone string `redis:"phone"`
age int `redis:"age"`
}
增删改查方法
存储、更新或从实体获取信息的方法示例。
这些方法是从 customersrepo 实体使用的。
他们收到包含信息的客户实体,并根据操作返回结果。
保存新记录
func (c *customerrepo) save(customer *customer) error {
return c.cli.client.hset(context.todo(), customer.id, customer).err()
}
获取id记录
func (c *customerrepo) get(id string) (*customer, error) {
customer := &customer{}
resmap := c.cli.client.hgetall(context.todo(), id)
if resmap.err() != nil {
return nil, resmap.err()
}
if len(resmap.val()) == 0 {
return nil, nil
}
err := resmap.scan(customer)
if err != nil {
return nil, err
}
return customer, nil
}
更新一条新记录
func (c *customerrepo) update(customer *customer) error {
return c.cli.client.hset(context.todo(), customer.id, customer).err()
}
删除一条新记录
func (c *CustomerRepo) Delete(id string) error {
return c.Cli.Client.Del(context.TODO(), id).Err()
}
查看代码示例
redis 测试示例









