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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package mobvista.dmp.datasource.iqiyi
import java.net.URI
import java.util
import java.util.concurrent.{Callable, CopyOnWriteArrayList, ExecutionException, ExecutorService, Executors, Future, LinkedBlockingDeque, LinkedBlockingQueue, ThreadFactory, ThreadPoolExecutor, TimeUnit}
import com.alibaba.fastjson.{JSONArray, JSONObject}
import com.google.common.util.concurrent.{FutureCallback, Futures, ListenableFuture, ListeningExecutorService, MoreExecutors, ThreadFactoryBuilder}
import mobvista.dmp.common.CommonSparkJob
import org.apache.commons.cli.Options
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.SparkEnv
import org.springframework.scheduling.concurrent.CustomizableThreadFactory
import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import java.net.InetAddress
class EtlIQiYiActivitionDaily extends CommonSparkJob with Serializable{
override protected def buildOptions(): Options = {
val options = new Options
options.addOption("outputdaily", true, "[must] outputdaily")
options.addOption("today", true, "[must] today")
options.addOption("last_req_day", true, "[must] last_req_day")
options
}
// def buildRes(iterator: Iterator[Row]): Iterator[ArrayBuffer[DeviceIdStatus]] = {
// println("executorId=="+SparkEnv.get.executorId)
// println("threadname=="+Thread.currentThread().getName())
// var ip: String = null
// var host: String = null
// val ia: InetAddress = InetAddress.getLocalHost
// host = ia.getHostName //获取计算机名字
// ip = ia.getHostAddress //获取IP
// println("host=="+host)
// println("ip=="+ip)
//
// // val poolExecutor = new ThreadPoolExecutor(1, 1, 500, TimeUnit.MILLISECONDS, new LinkedBlockingDeque[Runnable](500),
// // new CustomizableThreadFactory("AliRequest"), new ThreadPoolExecutor.CallerRunsPolicy())
// // val listeningExecutor = MoreExecutors.listeningDecorator(poolExecutor)
// // val newPoolExecutor = MoreExecutors.getExitingExecutorService(poolExecutor)
// // MoreExecutors.addDelayedShutdownHook(poolExecutor, 2, TimeUnit.SECONDS)
//
// val threadFactory: ThreadFactory = new ThreadFactoryBuilder().setNameFormat("EtlIQiYiActivitionDaily-async-pool-%d").build
// val threadPoolExecutor = new ThreadPoolExecutor(2, 2, 2, TimeUnit.MINUTES, new LinkedBlockingQueue[Runnable](), threadFactory)
// val listeningExecutor: ListeningExecutorService = MoreExecutors.listeningDecorator(threadPoolExecutor)
// val newPoolExecutor: ExecutorService = MoreExecutors.getExitingExecutorService(threadPoolExecutor)
// MoreExecutors.addDelayedShutdownHook(threadPoolExecutor, 2, TimeUnit.SECONDS)
//
//
// val res = new CopyOnWriteArrayList[ArrayBuffer[DeviceIdStatus]]()
// val futures = new CopyOnWriteArrayList[ListenableFuture[ArrayBuffer[DeviceIdStatus]]]()
// var tmpresult = ArrayBuffer[String]()
// while(iterator.hasNext) {
// if (tmpresult.length < 50) {
// val device_id_md5= iterator.next().getAs[String]("device_id_md5")
// tmpresult +=device_id_md5
// }
// if (tmpresult.length == 50) {
// val JoinDeviceId: String = tmpresult.mkString(",")
// val listenableFuture: ListenableFuture[ArrayBuffer[DeviceIdStatus]] = listeningExecutor.submit(new Callable[ArrayBuffer[DeviceIdStatus]]() {
// override def call(): ArrayBuffer[DeviceIdStatus] = {
// var tmpres: ArrayBuffer[DeviceIdStatus] = ArrayBuffer[DeviceIdStatus]()
// val jsonObject: JSONObject = IQiYiLaHuo.requestHttpQps(JoinDeviceId,"1","1")
// // println("22jsonObject22="+jsonObject)
// val data: JSONArray = jsonObject.getJSONArray("data")
// import scala.collection.JavaConversions._
// for (element <- data) {
// val element1: JSONObject = element.asInstanceOf[JSONObject]
// val deviceId: String = element1.getString("id")
// val status: String = element1.getString("status")
// tmpres += DeviceIdStatus(deviceId, status)
// }
// // println("res3333==="+tmpres)
// tmpres
// }
// })
//
// Futures.addCallback(listenableFuture, new FutureCallback[ArrayBuffer[DeviceIdStatus]] {
// override def onSuccess(result: ArrayBuffer[DeviceIdStatus]): Unit = {
// // println("res4444==="+res)
// res.add(result)
// println("success=")
// }
// override def onFailure(t: Throwable): Unit = {
// println("t.getMessage==="+t.getMessage)
// println("fail=")}
// }, newPoolExecutor)
// futures.add(listenableFuture)
// tmpresult.clear()
// }
// if (!iterator.hasNext) {
// if (tmpresult.nonEmpty) {
// println("tmpresult.length=="+tmpresult.length)
// val JoinDeviceId: String = tmpresult.mkString(",")
// val listenableFuture: ListenableFuture[ArrayBuffer[DeviceIdStatus]] = listeningExecutor.submit(new Callable[ArrayBuffer[DeviceIdStatus]]() {
// override def call(): ArrayBuffer[DeviceIdStatus] = {
// var tmpres: ArrayBuffer[DeviceIdStatus] = ArrayBuffer[DeviceIdStatus]()
// val jsonObject: JSONObject = IQiYiLaHuo.requestHttpQps(JoinDeviceId,"1","1")
// val data: JSONArray = jsonObject.getJSONArray("data")
// import scala.collection.JavaConversions._
// for (element <- data) {
// val element1: JSONObject = element.asInstanceOf[JSONObject]
// val deviceId: String = element1.getString("id")
// val status: String = element1.getString("status")
// tmpres += DeviceIdStatus(deviceId, status)
// }
// tmpres
// }
// })
//
// Futures.addCallback(listenableFuture, new FutureCallback[ArrayBuffer[DeviceIdStatus]] {
// override def onSuccess(result: ArrayBuffer[DeviceIdStatus]): Unit = {
// println("onSuccess=")
// res.add(result)}
//
// override def onFailure(t: Throwable): Unit = {
// // println("t.getMessage###"+t.getMessage)
// println("onFailure=")}
// }, newPoolExecutor)
// futures.add(listenableFuture)
// tmpresult.clear()
// }
// }
// }
// val allAsList = Futures.successfulAsList(futures)
// allAsList.get()
// // println("res5555==="+res)
// res.iterator().asScala
// }
// def buildRes(iterator: Iterator[Row]): Iterator[ArrayBuffer[DeviceIdStatus]] = {
// println("executorId=="+SparkEnv.get.executorId)
// println("threadname=="+Thread.currentThread().getName())
// var ip: String = null
// var host: String = null
// val ia: InetAddress = InetAddress.getLocalHost
// host = ia.getHostName //获取计算机名字
// ip = ia.getHostAddress //获取IP
// println("host=="+host)
// println("ip=="+ip)
//
// val tasks: util.List[Callable[ArrayBuffer[DeviceIdStatus]]] = new util.ArrayList[Callable[ArrayBuffer[DeviceIdStatus]]]
// var tmpresult = ArrayBuffer[String]()
// while(iterator.hasNext) {
// if (tmpresult.length < 50) {
// val device_id_md5= iterator.next().getAs[String]("device_id_md5")
// tmpresult +=device_id_md5
// }
// if (tmpresult.length == 50) {
// val JoinDeviceId: String = tmpresult.mkString(",")
// val callable: Callable[ArrayBuffer[DeviceIdStatus]] = new Callable[ArrayBuffer[DeviceIdStatus]]() {
// @throws[Exception]
// override def call: ArrayBuffer[DeviceIdStatus] = {
// var tmpres: ArrayBuffer[DeviceIdStatus] = ArrayBuffer[DeviceIdStatus]()
// val jsonObject: JSONObject = IQiYiLaHuo.requestHttpQps(JoinDeviceId,"1","1")
// val data: JSONArray = jsonObject.getJSONArray("data")
// import scala.collection.JavaConversions._
// for (element <- data) {
// val element1: JSONObject = element.asInstanceOf[JSONObject]
// val deviceId: String = element1.getString("id")
// val status: String = element1.getString("status")
// tmpres += DeviceIdStatus(deviceId, status)
// }
// tmpres
// }
// }
// tasks.add(callable)
// tmpresult.clear()
// }
// if (!iterator.hasNext) {
// if (tmpresult.nonEmpty) {
// println("tmpresult.length=="+tmpresult.length)
// val JoinDeviceId: String = tmpresult.mkString(",")
// val callable: Callable[ArrayBuffer[DeviceIdStatus]] = new Callable[ArrayBuffer[DeviceIdStatus]]() {
// @throws[Exception]
// override def call: ArrayBuffer[DeviceIdStatus] = {
// var tmpres: ArrayBuffer[DeviceIdStatus] = ArrayBuffer[DeviceIdStatus]()
// val jsonObject: JSONObject = IQiYiLaHuo.requestHttpQps(JoinDeviceId,"1","1")
// val data: JSONArray = jsonObject.getJSONArray("data")
// import scala.collection.JavaConversions._
// for (element <- data) {
// val element1: JSONObject = element.asInstanceOf[JSONObject]
// val deviceId: String = element1.getString("id")
// val status: String = element1.getString("status")
// tmpres += DeviceIdStatus(deviceId, status)
// }
// tmpres
// }
// }
// tasks.add(callable)
// tmpresult.clear()
// }
// }
// }
// val executorService: ExecutorService = Executors.newFixedThreadPool(5)
// var futures: util.List[Future[ArrayBuffer[DeviceIdStatus]]] = null
//
// try futures = executorService.invokeAll(tasks)
// catch {
// case e: InterruptedException =>
// e.printStackTrace()
// }
//
// val res = new CopyOnWriteArrayList[ArrayBuffer[DeviceIdStatus]]()
// import scala.collection.JavaConversions._
// for (future <- futures) {
// try {val value: ArrayBuffer[DeviceIdStatus] = future.get
// res.add(value)}
// catch {
// case e: InterruptedException =>
// e.printStackTrace()
// case e: ExecutionException =>
// e.printStackTrace()
// }
// }
// executorService.shutdown
// // println("res5555==="+res)
// res.iterator().asScala
// }
def buildRes(iterator: Iterator[Row]): Iterator[String] = {
println("executorId=="+SparkEnv.get.executorId)
println("threadname=="+Thread.currentThread().getName())
var ip: String = null
var host: String = null
val ia: InetAddress = InetAddress.getLocalHost
host = ia.getHostName //获取计算机名字
ip = ia.getHostAddress //获取IP
println("host=="+host)
println("ip=="+ip)
val tasks: util.List[Callable[String]] = new util.ArrayList[Callable[String]]
var tmpresult = ArrayBuffer[String]()
while(iterator.hasNext) {
if (tmpresult.length < 50) {
val device_id_md5= iterator.next().getAs[String]("device_id_md5")
tmpresult +=device_id_md5
}
if (tmpresult.length == 50) {
val JoinDeviceId: String = tmpresult.mkString(",")
val callable: Callable[String] = new Callable[String]() {
@throws[Exception]
override def call: String = {
val jsonObject: JSONObject = IQiYiLaHuo.requestHttpQps(JoinDeviceId,"1","1")
jsonObject.toString
}
}
tasks.add(callable)
tmpresult.clear()
}
if (!iterator.hasNext) {
if (tmpresult.nonEmpty) {
println("tmpresult.length=="+tmpresult.length)
val JoinDeviceId: String = tmpresult.mkString(",")
val callable: Callable[String] = new Callable[String]() {
@throws[Exception]
override def call: String = {
val jsonObject: JSONObject = IQiYiLaHuo.requestHttpQps(JoinDeviceId,"1","1")
jsonObject.toString
}
}
tasks.add(callable)
tmpresult.clear()
}
}
}
val executorService: ExecutorService = Executors.newFixedThreadPool(2)
var futures: util.List[Future[String]] = null
try futures = executorService.invokeAll(tasks)
catch {
case e: InterruptedException =>
e.printStackTrace()
}
val res = new CopyOnWriteArrayList[String]()
import scala.collection.JavaConversions._
for (future <- futures) {
try {val value: String = future.get
res.add(value)}
catch {
case e: InterruptedException =>
e.printStackTrace()
case e: ExecutionException =>
println("fail===")
e.printStackTrace()
}
}
executorService.shutdown
res.iterator().asScala
}
override protected def run(args: Array[String]): Int = {
val commandLine = commParser.parse(options, args)
if (!checkMustOption(commandLine)) {
printUsage(options)
return -1
} else printOptions(commandLine)
val outputdaily = commandLine.getOptionValue("outputdaily")
val today = commandLine.getOptionValue("today")
val last_req_day = commandLine.getOptionValue("last_req_day")
val spark = SparkSession.builder()
.appName("EtlAliActivitionDaily")
.config("spark.rdd.compress", "true")
.config("spark.io.compression.codec", "snappy")
.config("spark.sql.orc.filterPushdown", "true")
.config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.enableHiveSupport()
.getOrCreate()
import spark.implicits._
FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(outputdaily), true)
try {
var sql1=
s"""
|select XX.device_id_md5,XX.device_id,XX.device_type
|FROM (select X.device_id_md5,X.device_id,X.device_type,
|row_number() over(partition by X.device_id_md5 order by X.device_type asc) rk
|from ( select device_id,device_type,
|case when device_type = 'imei' then MD5(device_id) when device_type = 'imeimd5' then device_id end as device_id_md5
|from dwh.ods_dmp_user_info where dt ='${today}'
| and device_type in ('imei','imeimd5')
| and last_req_day >='${last_req_day}'
| and upper(country) = 'CN' ) X ) XX
| WHERE XX.rk= 1 limit 10000000
""".stripMargin
// spark.sql(sql1).rdd.map(_.mkString).coalesce(40).saveAsTextFile(outputdaily)
import spark.implicits._
// spark.sql(sql1).repartition(30).rdd.mapPartitions(rows => { buildRes(rows)}).flatMap(row =>row)
// .toDF.rdd.map(_.mkString("\t")).coalesce(30).saveAsTextFile(outputdaily)
spark.sql(sql1).repartition(30).rdd.mapPartitions(rows => { buildRes(rows)}).
coalesce(30).saveAsTextFile(outputdaily)
} finally {
spark.stop()
}
0
}
}
object EtlIQiYiActivitionDaily {
def main(args: Array[String]): Unit = {
new EtlIQiYiActivitionDaily().run(args)
}
}