上一篇中虽然解决了,单例RedisTemplate在事务和非事务中混用的问题,但是这两天又发现如果设置了RedisTemplate启用事务(设置 redisTemplate.setEnableTransactionSupport(true))时,如果在使用中不加@Transaction注解,会造成Redis连接不会释放的问题。
再来看一下RedisTemplate中的execute方法:
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
//如果设置了启用事务,则调用bindConnection
conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
} else {
conn = RedisConnectionUtils.getConnection(factory);
}
boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
//预留钩子函数可在执行具体操作前对connection做一些处理
RedisConnection connToUse = preProcessConnection(conn, existingConnection);
boolean pipelineStatus = connTo