Spring Data Redis SET命令支持EX和NX

时间:2017-02-17 10:05:58

标签: spring redis

Spring Data Redis支持使用Options

的SET命令

我的用例:

127.0.0.1:6379>设置lock.foo运行NX EX 20

然后检查Redis是否返回值OK或(nil)

2 个答案:

答案 0 :(得分:1)

使用RedisTemplate#execute(RedisCallback<T>方法,演示:

@Autowired
private RedisTemplate redisTemplate;

public void test() {
  String redisKey = "lock.foo";
  String value = "RUNNING";
  long expire = 20L;
  Boolean result = (Boolean) redisTemplate.execute((RedisCallback<Boolean>) connection -> {
    byte[] redisKeyBytes = redisTemplate.getKeySerializer().serialize(redisKey);
    byte[] valueBytes = redisTemplate.getValueSerializer().serialize(value);
    Expiration expiration = Expiration.from(expire, TimeUnit.SECONDS);
    return connection.set(redisKeyBytes, valueBytes, expiration, RedisStringCommands.SetOption.SET_IF_ABSENT);
  });
  System.out.println("result = " + result);
}

RedisTemplate配置:

@Configuration
public class RedisConfig {
  @Bean
  public RedisSerializer<String> keySerializer() {
    return new StringRedisSerializer();
  }
  @Bean
  public RedisSerializer<Object> valueSerializer() {
    return new GenericJackson2JsonRedisSerializer();
  }
  @Bean
  public RedisTemplate redisTemplate(RedisTemplate redisTemplate, RedisSerializer keySerializer, RedisSerializer valueSerializer) {
    //set key serializer
    redisTemplate.setKeySerializer(keySerializer);
    redisTemplate.setHashKeySerializer(keySerializer);
    //set value serializer
    redisTemplate.setValueSerializer(valueSerializer);
    redisTemplate.setHashValueSerializer(valueSerializer);
    return redisTemplate;
  }
}

答案 1 :(得分:0)

看不到任何Spring模板值操作解决方案,所以我在连接上做了'native'执行org.springframework.data.redis.connection.StringRedisConnection #execute(java.lang.String,java.lang.String .. 。) 然后由我来处理论证和结果。