ioredis#Redis TypeScript Examples

The following examples show how to use ioredis#Redis. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DatabaseContainer.ts    From ZenTS with MIT License 6 votes vote down vote up
constructor(dbConnection: Connection | null, redisClient: Redis | null) {
    if (dbConnection) {
      this.container.set(DB_TYPE.ORM, dbConnection)
    }

    if (redisClient) {
      this.container.set(DB_TYPE.REDIS, redisClient)
    }
  }
Example #2
Source File: hefeng-cached.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #3
Source File: redis-client.service.ts    From pknote-backend with GNU General Public License v3.0 5 votes vote down vote up
private _client: Redis;
Example #4
Source File: redis-client.service.ts    From pknote-backend with GNU General Public License v3.0 5 votes vote down vote up
async getClient(): Promise<Redis> {
    const client = this.redisService.getClient('main');
    return client;
  }
Example #5
Source File: RedisSessionStoreAdapter.ts    From ZenTS with MIT License 5 votes vote down vote up
protected readonly redisClient: Redis
Example #6
Source File: ModuleContext.ts    From ZenTS with MIT License 5 votes vote down vote up
public getRedisClient(): Redis {
    return this.databaseContainer.get(DB_TYPE.REDIS)
  }
Example #7
Source File: DatabaseContainer.ts    From ZenTS with MIT License 5 votes vote down vote up
protected container = new Map<DB_TYPE, Connection | Redis>()
Example #8
Source File: Registry.ts    From ZenTS with MIT License 5 votes vote down vote up
public getRedisClient(): Redis {
    return this.databaseContainer.get(DB_TYPE.REDIS)
  }
Example #9
Source File: WorkerQueue.ts    From lage with MIT License 5 votes vote down vote up
private coordinatorRedis: Redis;
Example #10
Source File: redis.ts    From ssmgr-trojan-client with MIT License 5 votes vote down vote up
private cl: Redis
Example #11
Source File: redis.ts    From ssmgr-trojan-client with MIT License 5 votes vote down vote up
constructor(redisClient: Redis) {
    super()
    this.cl = redisClient
  }
Example #12
Source File: pubsub.ts    From posthog-foss with MIT License 5 votes vote down vote up
private redis: Redis | null
Example #13
Source File: system.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #14
Source File: weixin.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #15
Source File: weixin.service.spec.ts    From life-helper-backend with MIT License 5 votes vote down vote up
describe('WeixinService', () => {
  let service: WeixinService
  let redisService: RedisService
  let redis: Redis

  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [WeixinService],
      imports: [SharedModule, RedisModule.register(RedisConfig)],
    }).compile()

    service = module.get<WeixinService>(WeixinService)
    redisService = module.get<RedisService>(RedisService)
    redis = redisService.getClient()
  })

  test('成功创建服务', async () => {
    expect(service).toBeDefined()
  })

  describe('[method] code2Session', () => {
    test('这个方式需要手动传入真实的 code,没办法自动化测试', () => {
      expect(service).toBeDefined()
    })
  })

  describe('[method] getAccessToken', () => {
    const redisKey = 'weixin:token'

    let token: string
    let token2: string

    test('预备环境,清除缓存中的 token', async () => {
      await redis.del(redisKey)
      const result = await redis.get(redisKey)
      expect(result).toBeNull()
    })

    test('第一次调用,调用成功', async () => {
      token = await service.getAccessToken()
      expect(token).toBeDefined()
    })

    test('直接从 Redis 中检查,返回 token 与存储 token 一致', async () => {
      const result = await redis.get(redisKey)
      expect(result).toBe(token)
    })

    test('第二次调用(本次应该从缓存中读取),返回结果一致', async () => {
      const result = await service.getAccessToken()
      expect(result).toBe(token)
    })

    test('第三次调用,加上强制更新参数,返回的 token 应改变', async () => {
      const result = await service.getAccessToken(true)
      expect(result).not.toBe(token)
      token2 = result
    })

    test('再次检查,第三次强制更新调用获得的 token 确实存入 Redis', async () => {
      const result = await redis.get(redisKey)
      expect(result).toBe(token2)
    })
  })

  afterAll(async () => {
    await redis.quit()
  })
})
Example #16
Source File: oss.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #17
Source File: lbsqq.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #18
Source File: token.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #19
Source File: qrcode.service.ts    From life-helper-backend with MIT License 5 votes vote down vote up
private readonly redis: Redis
Example #20
Source File: lbsqq.service.spec.ts    From life-helper-backend with MIT License 4 votes vote down vote up
describe('LbsqqService', () => {
  let service: LbsqqService
  let redisService: RedisService
  let redis: Redis

  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [LbsqqService],
      imports: [SharedModule, RedisModule.register(RedisConfig)],
    }).compile()

    service = module.get<LbsqqService>(LbsqqService)
    redisService = module.get<RedisService>(RedisService)
    redis = redisService.getClient()
  })

  test('成功创建服务', async () => {
    expect(service).toBeDefined()
  })

  describe('[method] getKey', () => {
    test('按照递增序列返回 `key`', () => {
      const list = LbsqqKeys
      for (let i = 0; i < list.length; i++) {
        const key = service.getKey()
        expect(key).toBe(list[i])
      }
    })
  })

  describe('[method] locateIp', () => {
    /** 用于测试的 IP 地址 */
    let ip: string

    /** Redis 键名 */
    let redisKey: string

    /** 方法调用结果 */
    let result: LocateIpResponse

    // 准备工作,随机 1 个 IP 地址用于测试(随机 IP 段: `36.96.0.0/9`)
    test('生成 1 个随机 IP 地址', async () => {
      const ip1 = 36
      const ip2 = Math.floor(Math.random() * (223 - 96)) + 96
      const ip3 = Math.floor(Math.random() * 255)
      const ip4 = Math.floor(Math.random() * 255)

      ip = `${ip1}.${ip2}.${ip3}.${ip4}`
      redisKey = `lbsqq:location:ip:${ip}`

      // 如果已有缓存则删除
      const cache = await redis.get(redisKey)
      if (cache) {
        await redis.del(redisKey)
      }

      expect(ip).toBeDefined()
    })

    test('方法调用成功', async () => {
      result = await service.locateIp(ip)
      expect(result).toBeDefined()
    })

    test('响应结果的状态码为 0(表示请求成功)', () => {
      expect(result.status).toBe(0)
    })

    test('请求的 IP 地址与响应数据中的请求 IP 相同', () => {
      expect(ip).toBe(result.result.ip)
    })

    test('响应数据被 Redis 缓存正确', async () => {
      const redisResult = await redis.get(redisKey)
      expect(JSON.parse(redisResult)).toEqual(result)
    })
  })

  describe('[method] geoLocationCoder', () => {
    // 随机生成 1 个国内的经纬度
    const longitude = Math.floor(Math.random() * 10000) / 10000 + 120
    const latitude = Math.floor(Math.random() * 10000) / 10000 + 30

    const redisKey = `lbsqq:address:location:${longitude},${latitude}`

    let result: GeoLocationCoderResponse

    test('随机经纬度生成成功', () => {
      expect(longitude).toBeDefined()
      expect(latitude).toBeDefined()
    })

    test('方法调用成功', async () => {
      result = await service.geoLocationCoder(longitude, latitude)
      expect(result).toBeDefined()
    })

    test('响应结果的状态码为 0(表示请求成功)', () => {
      expect(result.status).toBe(0)
    })

    test('响应数据被 Redis 缓存正确', async () => {
      const redisResult = await redis.get(redisKey)
      expect(JSON.parse(redisResult)).toEqual(result)
    })
  })

  afterAll(async () => {
    await redis.quit()
  })
})
Example #21
Source File: schedule.test.ts    From posthog-foss with MIT License 4 votes vote down vote up
describe('startSchedule', () => {
    let hub: Hub, piscina: Piscina, closeHub: () => Promise<void>, redis: Redis

    beforeEach(async () => {
        const workerThreads = 2
        const testCode = `
            async function runEveryMinute (meta) {
                throw new Error('lol')
            }
        `
        await resetTestDatabase(testCode)
        piscina = setupPiscina(workerThreads, 10)
        ;[hub, closeHub] = await createHub({ LOG_LEVEL: LogLevel.Log, SCHEDULE_LOCK_TTL: 3 })

        redis = await hub.redisPool.acquire()
        await redis.del(LOCKED_RESOURCE)
    })

    afterEach(async () => {
        await redis.del(LOCKED_RESOURCE)
        await hub.redisPool.release(redis)
        await delay(1000)
        await piscina.destroy()
        await closeHub()
    })

    test('redlock', async () => {
        const promises = [createPromise(), createPromise(), createPromise()]
        let i = 0

        let lock1 = false
        let lock2 = false
        let lock3 = false

        const schedule1 = await startSchedule(hub, piscina, () => {
            lock1 = true
            promises[i++].resolve()
        })

        await promises[0].promise

        expect(lock1).toBe(true)
        expect(lock2).toBe(false)
        expect(lock3).toBe(false)

        const schedule2 = await startSchedule(hub, piscina, () => {
            lock2 = true
            promises[i++].resolve()
        })
        const schedule3 = await startSchedule(hub, piscina, () => {
            lock3 = true
            promises[i++].resolve()
        })

        await schedule1.stopSchedule()

        await promises[1].promise

        expect(lock2 || lock3).toBe(true)

        if (lock3) {
            await schedule3.stopSchedule()
            await promises[2].promise
            expect(lock2).toBe(true)
            await schedule2.stopSchedule()
        } else {
            await schedule2.stopSchedule()
            await promises[2].promise
            expect(lock3).toBe(true)
            await schedule3.stopSchedule()
        }
    })

    describe('loading the schedule', () => {
        let schedule: ScheduleControl

        beforeEach(async () => {
            schedule = await startSchedule(hub, piscina)
        })

        afterEach(async () => {
            await schedule.stopSchedule()
        })

        test('loads successfully', async () => {
            expect(hub.pluginSchedule).toEqual({
                runEveryMinute: [39],
                runEveryHour: [],
                runEveryDay: [],
            })

            await resetTestDatabase(`
                async function runEveryDay (meta) {
                    throw new Error('lol')
                }
            `)

            await schedule.reloadSchedule()

            expect(hub.pluginSchedule).toEqual({
                runEveryMinute: [39],
                runEveryHour: [],
                runEveryDay: [],
            })
        })
    })
})