diff --git a/src/types/redis_string.cc b/src/types/redis_string.cc index e2f1ea6fc93..61ef7640129 100644 --- a/src/types/redis_string.cc +++ b/src/types/redis_string.cc @@ -371,28 +371,33 @@ rocksdb::Status String::MSet(const std::vector &pairs, uint64_t ttl, expire = now + ttl; } - // Data race, key string maybe overwrite by other key while didn't lock the key here, + // Data race, key string maybe overwrite by other key while didn't lock the keys here, // to improve the set performance std::string ns_key; + std::optional guard; + if (lock) { + std::vector lock_keys; + lock_keys.reserve(pairs.size()); + for (const StringPair &pair : pairs) { + AppendNamespacePrefix(pair.key, &ns_key); + lock_keys.emplace_back(ns_key); + } + guard.emplace(storage_->GetLockManager(), lock_keys); + } + + auto batch = storage_->GetWriteBatchBase(); + WriteBatchLogData log_data(kRedisString); + batch->PutLogData(log_data.Encode()); for (const auto &pair : pairs) { std::string bytes; Metadata metadata(kRedisString, false); metadata.expire = expire; metadata.Encode(&bytes); bytes.append(pair.value.data(), pair.value.size()); - auto batch = storage_->GetWriteBatchBase(); - WriteBatchLogData log_data(kRedisString); - batch->PutLogData(log_data.Encode()); AppendNamespacePrefix(pair.key, &ns_key); batch->Put(metadata_cf_handle_, ns_key, bytes); - std::optional guard; - if (lock) { - guard.emplace(storage_->GetLockManager(), ns_key); - } - auto s = storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch()); - if (!s.ok()) return s; } - return rocksdb::Status::OK(); + return storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch()); } rocksdb::Status String::MSetNX(const std::vector &pairs, uint64_t ttl, bool *flag) {