人工智能聊天 Ai-Chat 的 MySQL、Redis 和向量数据库配置与代码实现如下:
1. MySQL 数据库配置与实现1.1 Docker 部署 MySQL通过 Docker 快速部署 MySQL 8.0.32,并挂载数据目录和配置文件:
docker run -d -p 3306:3306 --name mysql8.0.32 -v /home/mysql/data:/var/lib/mysql -v /home/mysql/conf.d:/etc/mysql/conf.d --restart always -e MYSQL_ROOT_PASSWORD=123456 mysql:8.0.321.2 权限设置与登录- 设置远程访问权限:grant all privileges on *.* to 'root'@'%';
- 登录 MySQL:mysql -u root --default-character-set=utf8mb4 -p
1.3 Go 代码实现 MySQL 连接1.4 对话记录持久化实现- 数据结构定义:type ChatRecord struct { ID int64 `json:"id"` UserMsg string `json:"user_msg"` UserMsgTokens int `json:"user_msg_tokens"` UserMsgKeywords []string `json:"user_msg_keywords"` AIMsg string `json:"ai_msg"` AIMsgTokens int `json:"ai_msg_tokens"` ReqTokens int `json:"req_tokens"` CreateAt int64 `json:"create_at"`}
- 插入记录:func (data *chatRecordsData) Add(cr *ChatRecord) (err error) { sqlStr := "insert into chat_records(user_msg,user_msg_tokens,user_msg_keywords,ai_msg,ai_msg_tokens,req_tokens,create_at)values(?,?,?,?,?,?,?)" res, err := data.db.Exec(sqlStr, cr.UserMsg, cr.UserMsgTokens, strings.Join(cr.UserMsgKeywords, ","), cr.AIMsg, cr.AIMsgTokens, cr.ReqTokens, cr.CreateAt) if err != nil { return } cr.ID, _ = res.LastInsertId() return}
- 查询记录:func (data *chatRecordsData) GetById(id int64) (cr *ChatRecord, err error) { sqlStr := "select id,user_msg,user_msg_tokens,user_msg_keywords,ai_msg,ai_msg_tokens,req_tokens,create_at from chat_records where id = ?" row := data.db.QueryRow(sqlStr, id) cr = &ChatRecord{} var keywords string err = row.Scan(&cr.ID, &cr.UserMsg, &cr.UserMsgTokens, &keywords, &cr.AIMsg, &cr.AIMsgTokens, &cr.ReqTokens, &cr.CreateAt) if err != nil { return nil, err } cr.UserMsgKeywords = strings.Split(keywords, ",") return cr, err}
2. Redis 配置与实现2.1 Docker 部署 Redis通过 Docker 快速部署 Redis 7.0.10,并设置密码:
docker run --name redis -d -p 6379:6379 --restart always -v /home/redis/data:/data redis:7.0.10 redis-server --requirepass 1234562.2 Redis Key 前缀设置- 统一前缀管理:const SERVICEPREFIX = "ai_chat_service_"func GetKey(key string, parts ...string) string { key = SERVICEPREFIX + key if len(parts) == 0 { return key } key += "_" + strings.Join(parts, "_") return key}
2.3 Go 连接池实现- 连接池初始化:func getPool(cnf *config.Config) RedisPool { return &redisPool{ pool: sync.Pool{ New: func() any { rdb := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", cnf.Redis.Host, cnf.Redis.Port), Password: cnf.Redis.Pwd, }) return rdb }, }, }}
- 获取与释放连接:func (p *redisPool) Get() *redis.Client { client := p.pool.Get().(*redis.Client) if client.Ping(context.Background()).Err() != nil { client = p.pool.New().(*redis.Client) } return client}func (p *redisPool) Put(client *redis.Client) { if client.Ping(context.Background()).Err() != nil { return } p.pool.Put(client)}
2.4 上下文缓存实现- 数据结构定义:type ChatMessage struct { ID string `json:"id,omitempty"` PID string `json:"pid,omitempty"` Message openai.ChatCompletionMessage `json:"msg,omitempty"` Tokens int `json:"tokens,omitempty"`}
- 缓存操作:func (c *redisCache) Get(key string) (*ChatMessage, error) { key = getRedisKey(key) str, err := c.redisCli.Get(context.Background(), key).Result() if err == redis2.Nil { return nil, nil } if err != nil { return nil, err } value := &ChatMessage{} err = json.Unmarshal([]byte(str), value) return value, err}func (c *redisCache) Set(key string, value *ChatMessage, ttl int) error { bytes, err := json.Marshal(value) if err != nil { return err } str := string(bytes) return c.redisCli.SetEx(context.Background(), getRedisKey(key), str, time.Duration(ttl)*time.Second).Err()}
3. 向量数据库配置与实现3.1 初始化向量数据库客户端总结- MySQL:用于持久化存储对话记录,支持高并发查询和写入。
- Redis:用于缓存上下文信息,减少数据库查询压力,提升响应速度。
- 向量数据库:用于存储和检索向量数据,支持语义搜索和相似性匹配。
以上配置和代码实现了 Ai-Chat 系统的核心数据存储与缓存功能,确保系统高效稳定运行。