public boolean add ( String key , Object value , Integer expiration ) throws Exception { Jedis jedis = null ; try { jedis = this . jedisPool . getResource ( ) ; long begin = System . currentTimeMillis ( ) ; // 操作setnx与expire成功返回1，失败返回0，仅当均返回1时，实际操作成功 Long result = jedis . setnx ( SafeEncoder . encode ( key ) , serialize ( value ) ) ; if ( expiration > 0 ) { result = result & jedis . expire ( key , expiration ) ; } long end = System . currentTimeMillis ( ) ; if ( result == 1L ) { logger . info ( "add key:" + key + ", spends: " + ( end - begin ) + "ms" ) ; } else { logger . info ( "add key: " + key + " failed, key has already exists! " ) ; } return result == 1L ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; this . jedisPool . returnBrokenResource ( jedis ) ; throw e ; } finally { if ( jedis != null ) { this . jedisPool . returnResource ( jedis ) ; } } }
add if not exists