Skip to content

Commit 8c4f65d

Browse files
nnmehtaQuChen88
authored andcommitted
Make write operation to the cache async
Signed-off-by: Nihal Mehta <nnmehta@amazon.com>
1 parent cde3165 commit 8c4f65d

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

wrapper/src/main/java/software/amazon/jdbc/plugin/cache/CacheConnection.java

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import io.lettuce.core.RedisCommandExecutionException;
55
import io.lettuce.core.RedisURI;
66
import io.lettuce.core.api.StatefulRedisConnection;
7+
import io.lettuce.core.api.async.RedisAsyncCommands;
78
import io.lettuce.core.codec.ByteArrayCodec;
89
import io.lettuce.core.resource.ClientResources;
910
import software.amazon.jdbc.AwsWrapperProperty;
@@ -174,23 +175,42 @@ public byte[] readFromCache(String key) {
174175
}
175176

176177
public void writeToCache(String key, byte[] value, int expiry) {
177-
boolean isBroken = false;
178178
StatefulRedisConnection<byte[], byte[]> conn = null;
179179
try {
180180
initializeCacheConnectionIfNeeded(false);
181181
// get a connection from the write connection pool
182182
conn = writeConnectionPool.borrowObject();
183-
// TODO: make the write to the cache to be async.
184-
conn.sync().setex(computeHashDigest(key.getBytes(StandardCharsets.UTF_8)), expiry, value);
183+
// Add support to make write to the cache to be async.
184+
RedisAsyncCommands<byte[], byte[]> asyncCommands = conn.async();
185+
byte[] keyHash = computeHashDigest(key.getBytes(StandardCharsets.UTF_8));
186+
187+
StatefulRedisConnection<byte[], byte[]> finalConn = conn;
188+
asyncCommands.setex(keyHash, expiry, value)
189+
.whenComplete((result, exception) -> {
190+
if (exception != null) {
191+
LOGGER.warning("Failed to write to cache: " + exception.getMessage());
192+
if (writeConnectionPool != null) {
193+
try {
194+
returnConnectionBackToPool(finalConn, true, false);
195+
} catch (Exception ex) {
196+
LOGGER.warning("Error returning broken write connection back to pool: " + ex.getMessage());
197+
}
198+
}
199+
} else {
200+
if (writeConnectionPool != null) {
201+
try {
202+
returnConnectionBackToPool(finalConn, false, false);
203+
} catch (Exception ex) {
204+
LOGGER.warning("Error returning write connection back to pool: " + ex.getMessage());
205+
}
206+
}
207+
}
208+
});
185209
} catch (Exception e) {
186-
if (conn != null){
187-
isBroken = true;
188-
}
189210
LOGGER.warning("Failed to write to cache: " + e.getMessage());
190-
} finally {
191211
if (conn != null && writeConnectionPool != null) {
192212
try {
193-
this.returnConnectionBackToPool(conn, isBroken, false);
213+
returnConnectionBackToPool(conn, true, false);
194214
} catch (Exception ex) {
195215
LOGGER.warning("Error closing write connection: " + ex.getMessage());
196216
}

0 commit comments

Comments
 (0)