@@ -3,13 +3,90 @@ package service
33import (
44 "EasyTools/app/connect/redis/internal/define"
55 "EasyTools/app/connect/redis/internal/helper"
6+ "context"
67 "encoding/json"
78 "errors"
8- uuid "github.com/satori/go.uuid"
9+ "fmt"
10+ "net"
911 "os"
1012 "path/filepath"
13+ "time"
14+
15+ "github.com/go-redis/redis/v8"
16+ uuid "github.com/satori/go.uuid"
17+ "golang.org/x/crypto/ssh"
1118)
1219
20+ // ConnectionTest 测试连接
21+ func ConnectionTest (conn * define.Connection ) error {
22+ if conn .Addr == "" {
23+ return errors .New ("连接地址不能为空" )
24+ }
25+ if conn .Port == "" {
26+ conn .Port = "6379"
27+ }
28+
29+ // 创建 Redis 客户端配置
30+ redisOpts := & redis.Options {
31+ Addr : fmt .Sprintf ("%s:%s" , conn .Addr , conn .Port ),
32+ Password : conn .Password ,
33+ DB : 0 , // 默认数据库
34+ }
35+
36+ var rdb * redis.Client
37+ var sshClient * ssh.Client
38+
39+ // 如果是 SSH 连接,先建立 SSH 隧道
40+ if conn .Type == "ssh" && conn .SSHAddr != "" {
41+ sshConfig := & ssh.ClientConfig {
42+ User : conn .SSHUsername ,
43+ Auth : []ssh.AuthMethod {
44+ ssh .Password (conn .SSHPassword ),
45+ },
46+ HostKeyCallback : ssh .InsecureIgnoreHostKey (),
47+ Timeout : 10 * time .Second ,
48+ }
49+
50+ // 建立 SSH 连接
51+ var err error
52+ sshClient , err = ssh .Dial ("tcp" , fmt .Sprintf ("%s:%s" , conn .SSHAddr , conn .SSHPort ), sshConfig )
53+ if err != nil {
54+ return fmt .Errorf ("SSH连接失败: %v" , err )
55+ }
56+ defer sshClient .Close ()
57+
58+ // 通过 SSH 隧道建立 Redis 连接
59+ sshConn , err := sshClient .Dial ("tcp" , fmt .Sprintf ("%s:%s" , conn .Addr , conn .Port ))
60+ if err != nil {
61+ return fmt .Errorf ("通过SSH连接Redis失败: %v" , err )
62+ }
63+ defer sshConn .Close ()
64+
65+ // 使用自定义拨号器
66+ redisOpts .Dialer = func (ctx context.Context , network , addr string ) (net.Conn , error ) {
67+ return sshClient .Dial (network , addr )
68+ }
69+ // 重置地址为本地,因为实际连接是通过 SSH 隧道
70+ redisOpts .Addr = "127.0.0.1:6379"
71+ }
72+
73+ // 创建 Redis 客户端
74+ rdb = redis .NewClient (redisOpts )
75+ defer rdb .Close ()
76+
77+ // 测试连接
78+ ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
79+ defer cancel ()
80+
81+ // 执行 PING 命令测试连接
82+ _ , err := rdb .Ping (ctx ).Result ()
83+ if err != nil {
84+ return fmt .Errorf ("Redis连接测试失败: %v" , err )
85+ }
86+
87+ return nil
88+ }
89+
1390// ConnectionList 连接列表
1491func ConnectionList () ([]* define.Connection , error ) {
1592 baseDir := helper .GetAppBaseDir ()
0 commit comments