dockerfile修改
This commit is contained in:
56
internal/redis/client.go
Normal file
56
internal/redis/client.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const UserZSet = "chat:users"
|
||||
|
||||
type Client struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
// NewClient 创建 Redis 客户端
|
||||
func NewClient(addr string, password string, db int) (*Client, error) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: addr,
|
||||
Password: password,
|
||||
DB: db,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
return nil, fmt.Errorf("redis ping error: %w", err)
|
||||
}
|
||||
|
||||
return &Client{rdb: rdb}, nil
|
||||
}
|
||||
|
||||
// Close 关闭连接
|
||||
func (c *Client) Close() error {
|
||||
return c.rdb.Close()
|
||||
}
|
||||
|
||||
// AddUserToZSet 添加用户到 ZSet
|
||||
func (c *Client) AddUserToZSet(key string, user string, score int64) error {
|
||||
return c.rdb.ZAdd(context.Background(), key, redis.Z{
|
||||
Score: float64(score),
|
||||
Member: user,
|
||||
}).Err()
|
||||
}
|
||||
|
||||
// RemoveUserFromZSet 从 ZSet 移除用户
|
||||
func (c *Client) RemoveUserFromZSet(key string, user string) error {
|
||||
return c.rdb.ZRem(context.Background(), key, user).Err()
|
||||
}
|
||||
|
||||
// CountUsers 获取在线用户数
|
||||
func (c *Client) CountUsers(key string) (int64, error) {
|
||||
return c.rdb.ZCard(context.Background(), key).Result()
|
||||
}
|
||||
Reference in New Issue
Block a user