Skip to content

Use extended SET instead of deprecated setEx, pSetEx and setNX commands #2900

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
Expand All @@ -37,6 +35,7 @@
* @author Jennifer Hickey
* @author Christoph Strobl
* @author Jiahe Cai
* @author Ehsan Alemzadeh
*/
class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements ValueOperations<K, V> {

Expand Down Expand Up @@ -250,43 +249,15 @@ public void set(K key, V value, long timeout, TimeUnit unit) {
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);

execute(new RedisCallback<Object>() {

@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {

potentiallyUsePsetEx(connection);
return null;
}

public void potentiallyUsePsetEx(RedisConnection connection) {

if (!TimeUnit.MILLISECONDS.equals(unit) || !failsafeInvokePsetEx(connection)) {
connection.setEx(rawKey, TimeoutUtils.toSeconds(timeout, unit), rawValue);
}
}

private boolean failsafeInvokePsetEx(RedisConnection connection) {

boolean failed = false;
try {
connection.pSetEx(rawKey, timeout, rawValue);
} catch (UnsupportedOperationException ignore) {
// in case the connection does not support pSetEx return false to allow fallback to other operation.
failed = true;
}
return !failed;
}

});
execute(connection -> connection.set(rawKey, rawValue, Expiration.from(timeout, unit), SetOption.upsert()));
}

@Override
public Boolean setIfAbsent(K key, V value) {

byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.setNX(rawKey, rawValue));
return execute(connection -> connection.set(rawKey, rawValue, Expiration.persistent(), SetOption.ifAbsent()));
}

@Override
Expand Down