|
47 | 47 | */ |
48 | 48 | public class RedisOutputFormat extends AbstractDtRichOutputFormat<Tuple2> { |
49 | 49 | private static final Logger LOG = LoggerFactory.getLogger(RedisOutputFormat.class); |
| 50 | + |
50 | 51 | protected String[] fieldNames; |
| 52 | + |
51 | 53 | protected TypeInformation<?>[] fieldTypes; |
| 54 | + |
52 | 55 | protected List<String> primaryKeys; |
| 56 | + |
53 | 57 | protected int timeout = 10000; |
| 58 | + |
54 | 59 | private String url; |
| 60 | + |
55 | 61 | private String database = "0"; |
| 62 | + |
56 | 63 | private String tableName; |
| 64 | + |
57 | 65 | private String password; |
| 66 | + |
58 | 67 | private int redisType; |
| 68 | + |
59 | 69 | private String maxTotal; |
| 70 | + |
60 | 71 | private String maxIdle; |
| 72 | + |
61 | 73 | private String minIdle; |
| 74 | + |
62 | 75 | private String masterName; |
| 76 | + |
| 77 | + protected int keyExpiredTime; |
| 78 | + |
63 | 79 | private JedisPool pool; |
64 | 80 |
|
65 | 81 | private JedisCommands jedis; |
@@ -146,15 +162,31 @@ public void writeRecord(Tuple2 record) throws IOException { |
146 | 162 | for (int i = 0; i < fieldNames.length; i++) { |
147 | 163 | refData.put(fieldNames[i], row.getField(i)); |
148 | 164 | } |
149 | | - String redisKey = buildCacheKey(refData); |
150 | | - refData.forEach((key, value) -> jedis.hset(redisKey, key, String.valueOf(value))); |
151 | | - |
| 165 | + save(refData); |
152 | 166 | if (outRecords.getCount() % ROW_PRINT_FREQUENCY == 0) { |
153 | 167 | LOG.info(record.toString()); |
154 | 168 | } |
155 | 169 | outRecords.inc(); |
156 | 170 | } |
157 | 171 |
|
| 172 | + |
| 173 | + /** |
| 174 | + * 1. build key from map. |
| 175 | + * 2. save key and value. |
| 176 | + * 3. set expired time for key when keyExpiredTime has been set. |
| 177 | + * @param refData |
| 178 | + */ |
| 179 | + private synchronized void save(Map<String, Object> refData) { |
| 180 | + String key = buildCacheKey(refData); |
| 181 | + try { |
| 182 | + refData.forEach((field, value) -> jedis.hset(key, field, String.valueOf(value))); |
| 183 | + } finally { |
| 184 | + if (keyExpiredTime != 0) { |
| 185 | + jedis.expire(key, keyExpiredTime); |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + |
158 | 190 | @Override |
159 | 191 | public void close() throws IOException { |
160 | 192 | if (jedisSentinelPool != null) { |
@@ -254,6 +286,11 @@ public RedisOutputFormatBuilder setMasterName(String masterName) { |
254 | 286 | return this; |
255 | 287 | } |
256 | 288 |
|
| 289 | + public RedisOutputFormatBuilder setKeyExpiredTime(int keyExpiredTime){ |
| 290 | + redisOutputFormat.keyExpiredTime = keyExpiredTime; |
| 291 | + return this; |
| 292 | + } |
| 293 | + |
257 | 294 | public RedisOutputFormat finish() { |
258 | 295 | if (redisOutputFormat.url == null) { |
259 | 296 | throw new IllegalArgumentException("No URL supplied."); |
|
0 commit comments