addKeysToCacheBatch 批量添加密钥到缓存(用于批量导入场景)
(groupID uint, keys []models.APIKey)
| 574 | |
| 575 | // addKeysToCacheBatch 批量添加密钥到缓存(用于批量导入场景) |
| 576 | func (p *KeyProvider) addKeysToCacheBatch(groupID uint, keys []models.APIKey) error { |
| 577 | if len(keys) == 0 { |
| 578 | return nil |
| 579 | } |
| 580 | |
| 581 | // 1. 批量 HSet 密钥详情 |
| 582 | if pipeliner, ok := p.store.(store.RedisPipeliner); ok { |
| 583 | // Redis: 使用 Pipeline 批量操作 |
| 584 | pipe := pipeliner.Pipeline() |
| 585 | for i := range keys { |
| 586 | keyHashKey := fmt.Sprintf("key:%d", keys[i].ID) |
| 587 | pipe.HSet(keyHashKey, p.apiKeyToMap(&keys[i])) |
| 588 | } |
| 589 | if err := pipe.Exec(); err != nil { |
| 590 | return fmt.Errorf("failed to batch HSet keys: %w", err) |
| 591 | } |
| 592 | } else { |
| 593 | // MemoryStore: 降级为逐个 HSet |
| 594 | for i := range keys { |
| 595 | keyHashKey := fmt.Sprintf("key:%d", keys[i].ID) |
| 596 | if err := p.store.HSet(keyHashKey, p.apiKeyToMap(&keys[i])); err != nil { |
| 597 | return fmt.Errorf("failed to HSet key %d: %w", keys[i].ID, err) |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | // 2. 收集所有密钥 ID |
| 603 | activeKeysListKey := fmt.Sprintf("group:%d:active_keys", groupID) |
| 604 | activeKeyIDs := make([]any, len(keys)) |
| 605 | for i := range keys { |
| 606 | activeKeyIDs[i] = keys[i].ID |
| 607 | } |
| 608 | |
| 609 | // 3. 批量 LPush 活跃密钥 |
| 610 | if err := p.store.LPush(activeKeysListKey, activeKeyIDs...); err != nil { |
| 611 | return fmt.Errorf("failed to batch LPush keys to group %d: %w", groupID, err) |
| 612 | } |
| 613 | |
| 614 | return nil |
| 615 | } |
| 616 | |
| 617 | // removeKeyFromStore is a helper to remove a single key from the cache. |
| 618 | func (p *KeyProvider) removeKeyFromStore(keyID, groupID uint) error { |