Skip to content

Commit 94e8724

Browse files
committed
feat: add methods to check if there are connection errors and to reconnect all connections
1 parent 4cdda92 commit 94e8724

1 file changed

Lines changed: 42 additions & 1 deletion

File tree

src/main/kotlin/dev/bypixel/lettucewrapper/LettuceRedisClient.kt

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import kotlinx.coroutines.launch
2424
import kotlinx.coroutines.sync.Semaphore
2525
import kotlinx.coroutines.sync.withPermit
2626
import kotlinx.coroutines.withContext
27-
import kotlinx.serialization.Serializable
2827
import kotlinx.serialization.json.Json
2928
import org.json.JSONObject
3029
import java.io.FileInputStream
@@ -99,6 +98,48 @@ class LettuceRedisClient(
9998

10099
val connection: StatefulRedisConnection<String, String> = redisClient.connect()
101100

101+
suspend fun reconnectAll() = withContext(Dispatchers.IO) {
102+
val semaphore = Semaphore(pool.size)
103+
coroutineScope.launch {
104+
pool.forEach { conn ->
105+
launch {
106+
semaphore.withPermit {
107+
if (conn.isOpen) {
108+
conn.close()
109+
}
110+
val newConn = redisClient.connect(StringCodec.UTF8)
111+
val index = pool.indexOf(conn)
112+
pool[index] = newConn
113+
}
114+
}
115+
}
116+
}.join()
117+
}
118+
119+
suspend fun checkConnectionErrors(): List<Throwable> = withContext(Dispatchers.IO) {
120+
val errors = mutableListOf<Throwable>()
121+
val semaphore = Semaphore(pool.size)
122+
coroutineScope.launch {
123+
pool.forEach { conn ->
124+
launch {
125+
semaphore.withPermit {
126+
if (!conn.isOpen) {
127+
errors.add(Exception("Connection is closed"))
128+
} else {
129+
val pingCommand = conn.async().ping()
130+
try {
131+
pingCommand.await()
132+
} catch (e: Exception) {
133+
errors.add(e)
134+
}
135+
}
136+
}
137+
}
138+
}
139+
}.join()
140+
errors
141+
}
142+
102143
suspend inline fun <T> withAsync(
103144
crossinline block: suspend (RedisAsyncCommands<String, String>) -> T
104145
): T = block(nextConnection().async())

0 commit comments

Comments
 (0)