-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathRedisInputDStream.scala
80 lines (69 loc) · 2.46 KB
/
RedisInputDStream.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.redislabs.provider.redis.streaming
import com.redislabs.provider.redis.RedisConfig
import org.apache.curator.utils.ThreadUtils
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.receiver.Receiver
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import redis.clients.jedis._
import scala.reflect.{ClassTag, classTag}
import scala.util.control.NonFatal
class RedisInputDStream[T: ClassTag](_ssc: StreamingContext,
keys: Array[String],
storageLevel: StorageLevel,
redisConfig: RedisConfig,
streamType: Class[T])
extends ReceiverInputDStream[T](_ssc) {
def getReceiver(): Receiver[T] = {
new RedisReceiver(keys, storageLevel, redisConfig, streamType)
}
}
private class RedisReceiver[T: ClassTag](keys: Array[String],
storageLevel: StorageLevel,
redisConfig: RedisConfig,
streamType: Class[T])
extends Receiver[T](storageLevel) {
var jedisConnect: Jedis = null
def onStart() {
val executorPool = ThreadUtils.newFixedThreadPool(keys.length, "BlockLists Streaming")
try {
/* start a executor for each interested List */
keys.foreach{ key =>{
jedisConnect = redisConfig.connectionForKey(key)
executorPool.submit(new MessageHandler(jedisConnect, key))
}
}
} finally {
executorPool.shutdown()
}
}
def onStop() {
/* quit the connect*/
if (jedisConnect != null) {
jedisConnect.quit()
jedisConnect = null
}
}
private class MessageHandler(conn: Jedis, key: String) extends Runnable {
def run() {
try {
while(!isStopped) {
val response = conn.blpop(2, key)
if (response == null || response.isEmpty) {
} else if (classTag[T] == classTag[String]) {
store(response.get(1).asInstanceOf[T])
} else if (classTag[T] == classTag[(String, String)]) {
store((response.get(0), response.get(1)).asInstanceOf[T])
} else {
throw new scala.Exception("Unknown Redis Streaming type")
}
}
} catch {
case NonFatal(e) =>
restart("Error receiving data", e)
} finally {
onStop()
}
}
}
}