@@ -75,6 +75,8 @@ public class RedisOutputFormat extends AbstractDtRichOutputFormat<Tuple2> {
7575
7676 protected int timeout ;
7777
78+ protected long keyExpiredTime ;
79+
7880 private JedisPool pool ;
7981
8082 private JedisCommands jedis ;
@@ -188,7 +190,7 @@ public void writeRecord(Tuple2 record) throws IOException {
188190 if (field != null ) {
189191 value = field .toString ();
190192 }
191- jedis . set (key .toString (), value );
193+ saveKey (key .toString (), value );
192194 }
193195
194196 if (outRecords .getCount () % ROW_PRINT_FREQUENCY == 0 ){
@@ -197,6 +199,24 @@ public void writeRecord(Tuple2 record) throws IOException {
197199 outRecords .inc ();
198200 }
199201
202+ /**
203+ * 1. save key and value.
204+ * 2. set expired time for key when keyExpiredTime has been set.
205+ * @param key
206+ * @param value
207+ */
208+ private void saveKey (String key , String value ) {
209+ if (keyExpiredTime != 0L ) {
210+ boolean keyExist = jedis .exists (key );
211+ if (keyExist ) {
212+ jedis .del (key );
213+ }
214+ jedis .set (key , value , "NX" , "PX" , keyExpiredTime );
215+ } else {
216+ jedis .set (key , value );
217+ }
218+ }
219+
200220 @ Override
201221 public void close () throws IOException {
202222 if (jedisSentinelPool != null ) {
@@ -289,6 +309,11 @@ public RedisOutputFormatBuilder setMasterName(String masterName){
289309 return this ;
290310 }
291311
312+ public RedisOutputFormatBuilder setKeyExpiredTime (long keyExpiredTime ){
313+ redisOutputFormat .keyExpiredTime = keyExpiredTime ;
314+ return this ;
315+ }
316+
292317 public RedisOutputFormat finish (){
293318 if (redisOutputFormat .url == null ){
294319 throw new IllegalArgumentException ("No URL supplied." );
0 commit comments