@@ -97,17 +97,31 @@ export class RedisCache {
9797 }
9898
9999 // 清除无效的缓存
100- async clearUseless ( ) {
100+ async clearUseless ( match = '*' ) {
101101 const now = _ . now ( )
102- const keys1 = await this . io . keys ( this . key ( '*' ) )
102+ const keys1 = await this . io . keys ( this . key ( match ) )
103+ const result = { } as Record < string , [ number , number ] >
104+ // 循环处理每一个key
103105 for ( const key1 of keys1 ) {
106+ // 按1000分组
104107 const keys2 = await this . io . hkeys ( key1 )
105- for ( const key2 of keys2 ) {
106- const value = ( await this . io . hget ( key1 , key2 ) ) ?? ''
107- const expire = _ . toInteger ( value . substr ( 1 , 13 ) )
108- if ( expire < now ) await this . io . hdel ( key1 , key2 )
108+ const keys2Chunks = _ . chunk ( keys2 , 1000 )
109+ result [ key1 ] = [ 0 , keys2 . length ]
110+ for ( const keys2 of keys2Chunks ) {
111+ // 批量获取
112+ const values = await this . io . hmget ( key1 , keys2 )
113+ const deleteIds = [ ] as string [ ]
114+ // 判断是否过期
115+ _ . forEach ( values , ( value , index ) => {
116+ const expire = _ . toInteger ( ( value || '' ) . substring ( 1 , 14 ) )
117+ if ( expire < now ) deleteIds . push ( keys2 [ index ] )
118+ } )
119+ // 删除过期的
120+ if ( deleteIds . length ) await this . io . hdel ( key1 , ...deleteIds )
121+ result [ key1 ] [ 0 ] += deleteIds . length
109122 }
110123 }
124+ return result
111125 }
112126
113127 // 清除指定命名空间的缓存
0 commit comments