蛋疼问题,想使用
setIfAbsent(Object key, Object value, long timeout, TimeUnit unit)
方法解决多点和并发问题,但是由于redis版本问题不存在,只好曲线救国
- springboot 2.0.2
- springboot-redis 2.0.7
- jedis 2.9.0
解决思路
1.没有就给他造一个,首先超看redis支持不支持,在查看存在该方法的源码;发现最终实现方法是在RedisStringCommands.class里面
使用的版本redis 方法中存在该方法,重新实现即可
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
RedisSerializer keySerializer() {
return this.redisTemplate.getKeySerializer();
}
RedisSerializer valueSerializer() {
return this.redisTemplate.getValueSerializer();
}
byte[] rawKey(Object key) {
Assert.notNull(key, "non null key required");
return this.keySerializer() == null && key instanceof byte[] ? (byte[])((byte[])key) : this.keySerializer().serialize(key);
}
byte[] rawValue(Object value) {
return this.valueSerializer() == null && value instanceof byte[] ? (byte[])((byte[])value) : this.valueSerializer().serialize(value);
}
/**
*
* @param key
* @param value
* @param timeout
* @param unit
* @return
*/
public Boolean setIfAbsent(Object key, Object value, long timeout, TimeUnit unit) {
byte[] rawKey = this.rawKey(key);
byte[] rawValue = this.rawValue(value);
Expiration expiration = Expiration.from(timeout, unit);
return (Boolean)this.redisTemplate.execute((connection) -> {
return connection.set(rawKey, rawValue, expiration, RedisStringCommands.SetOption.ifAbsent());
}, true);
}
}
网友评论