import { Service } from 'egg' ; import ApiException from '../exception/ApiException' ; import { ApiResponseCode } from '../response/responseCode' ; import { ApiResponseMsg } from '../response/responseMsg' ; const SUCCESS_REDIS = 'OK' ; export default class Redis extends Service { public async set ( key , value ) { const docs = await this . app . redis . set ( key , value ) ; if ( docs === SUCCESS_REDIS ) { return true ; } this . app . logger . info ( 'redis 储存错误 ------> error' , docs ) ; throw new ApiException ( ApiResponseCode . SERVER_ERROR , ApiResponseMsg . SERVER_ERROR ) ; } public async setex ( key , value , expire ) { const docs = await this . app . redis . setex ( key , expire , value ) ; if ( docs === SUCCESS_REDIS ) { return true ; } this . app . logger . info ( 'redis 储存错误 ------> error' , docs ) ; throw new ApiException ( ApiResponseCode . SERVER_ERROR , ApiResponseMsg . SERVER_ERROR ) ; } public async get ( key ) { return await this . app . redis . get ( key ) ; } public async setMap ( key , value ) { const docs = await this . app . redis . hmset ( key , value ) ; if ( docs === SUCCESS_REDIS ) { return true ; } this . app . logger . info ( 'redis 储存错误 ------> error' , docs ) ; throw new ApiException ( ApiResponseCode . SERVER_ERROR , ApiResponseMsg . SERVER_ERROR ) ; } public async getMap < T extends any > ( key ) { const data = await this . app . redis . hgetall ( key ) ; return data ? data as T : null ; } }