今天在測試代碼的時候無意中發現,使用springboot-redis連接的Redis,在讀寫數據的時候,日志中總是打印“Opening RedisConnection” “Closing Redis Connection”;
13:22:46.343 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Opening RedisConnection
13:22:46.346 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Closing Redis Connection
13:22:46.347 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Opening RedisConnection
13:22:46.349 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Closing Redis Connection
13:22:46.349 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Opening RedisConnection
13:22:46.351 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Closing Redis Connection
13:22:46.351 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Opening RedisConnection
13:22:46.353 [LService-16] DEBUG o.s.d.r.core.RedisConnectionUtils - Closing Redis Connection
是不是每一次的讀寫都在創建和銷毀連接?那豈不是很耗費資源?是不是效率很低下???
其實,並不是這樣的。閱讀源代碼我們可以發現我們對redis的所有操作都是通過回調execute函數執行的,spring-boot-redis內部為我們封裝管理了連接池;性能那塊也不用擔心。
public <T> T execute(RedisCallback<T> action, boolean exposeConnection) {
return execute(action, exposeConnection, false);
}
// execute實現如下:
// org.springframework.data.redis.core.RedisTemplate<K, V> --- 最終實現
public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
Assert.notNull(action, "Callback object must not be null");
RedisConnectionFactory factory = getConnectionFactory();
RedisConnection conn = null;
try {
if (enableTransactionSupport) {
// only bind resources in case of potential transaction synchronization
conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
} else {
conn = RedisConnectionUtils.getConnection(factory);
}
boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
RedisConnection connToUse = preProcessConnection(conn, existingConnection);
boolean pipelineStatus = connToUse.isPipelined();
if (pipeline && !pipelineStatus) {
connToUse.openPipeline();
}
RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
T result = action.doInRedis(connToExpose);
// close pipeline
if (pipeline && !pipelineStatus) {
connToUse.closePipeline();
}
// TODO: any other connection processing?
return postProcessResult(result, connToUse, existingConnection);
} finally {
if (!enableTransactionSupport) {
RedisConnectionUtils.releaseConnection(conn, factory);
}
}
}
這里面每次執行action.doInRedis(connToExpose)前都要調用RedisConnectionUtils.getConnection(factory);獲得一個連接,進入RedisConnnectionUtils類中,getConnection(factory)最終調用的是doGetConnection(factory, true, false, enableTranactionSupport)這個函數。
這個函數我們可以看下api文檔,發現實際上並不是真的創建一個新的redis連接,它只是在connectFactory中獲取一個連接,也就是從連接池中取出一個連接。當然如果connectFactory沒有連接可用,此時如果allowCreate=true便會創建出一個新的連接,並且加入到connectFactory中。
這樣就可以放心大膽的使用,而不用擔心性能問題了。。。