File size: 2,138 Bytes
330c0d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import cfg from "./config.js"
import { createClient } from "redis"
import { exec } from "node:child_process"

/**
 * 初始化全局redis客户端
 */
export default async function redisInit() {
  const rc = cfg.redis
  if (!rc?.open) return
  const redisUn = rc.username || ""
  let redisPw = rc.password ? `:${rc.password}` : ""
  if (rc.username || rc.password)
    redisPw += "@"
  const redisUrl = `redis://${redisUn}${redisPw}${rc.host}:${rc.port}/${rc.db}`
  let client = createClient({ url: redisUrl })

  try {
    logger.info(`正在连接 ${logger.blue(redisUrl)}`)
    await client.connect()
  } catch (err) {
    logger.error(`Redis 错误:${logger.red(err)}`)

    const cmd = "redis-server --save 900 1 --save 300 10 --daemonize yes" + await aarch64()
    logger.info("正在启动 Redis...")
    await execSync(cmd)
    await new Promise((resolve) => setTimeout(resolve, 1000))

    try {
      client = createClient({ url: redisUrl })
      await client.connect()
    } catch (err) {
      logger.error(`Redis 错误:${logger.red(err)}`)
      logger.error(`请先启动 Redis:${logger.blue(cmd)}`)
      process.exit()
    }
  }

  client.on("error", async err => {
    logger.error(`Redis 错误:${logger.red(err)}`)
    const cmd = "redis-server --save 900 1 --save 300 10 --daemonize yes" + await aarch64()
    logger.error(`请先启动 Redis:${cmd}`)
    process.exit()
  })

  /** 全局变量 redis */
  global.redis = client
  logger.info("Redis 连接成功")
  return client
}

async function aarch64() {
  if (process.platform == "win32")
    return ""
  /** 判断arch */
  const arch = await execSync("uname -m")
  if (arch.stdout && arch.stdout.includes("aarch64")) {
    /** 判断redis版本 */
    let v = await execSync("redis-server -v")
    if (v.stdout) {
      v = v.stdout.match(/v=(\d)./)
      /** 忽略arm警告 */
      if (v && v[1] >= 6)
        return " --ignore-warnings ARM64-COW-BUG"
    }
  }
  return ""
}

function execSync (cmd) {
  return new Promise((resolve, reject) => {
    exec(cmd, (error, stdout, stderr) => {
      resolve({ error, stdout, stderr })
    })
  })
}