1)PropertiesUtil 获取配置文件的工具类
import java.io.InputStreamReader
import java.util.Properties
object PropertiesUtil {
def load(propertieName:String): Properties ={
val prop=new Properties()
prop.load(new InputStreamReader(Thread.currentThread().getContextClassLoader.getResourceAsStream(propertieName) , "UTF-8"))
prop
}
}
2)MykafkaUtil 获取kafak连接的工具类
import java.util.Properties
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.dstream.InputDStream
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
object MyKafkaUtil {
private val properties: Properties = PropertiesUtil.load("config.properties")
val broker_list: String = properties.getProperty("kafka.broker.list")
val kafkaParam = Map(
"bootstrap.servers" -> broker_list,
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "bigdata2020",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (true: java.lang.Boolean)
)
def getKafkaStream(topic: String, ssc: StreamingContext): InputDStream[ConsumerRecord[String, String]] = {
val dStream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
ssc,
LocationStrategies.PreferConsistent,
ConsumerStrategies.Subscribe[String, String](Array(topic), kafkaParam))
dStream
}
}
3)RedisUtil 获取redis连接的工具类
import java.util.Properties
import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}
object RedisUtil {
var jedisPool: JedisPool = _
def getJedisClient: Jedis = {
if (jedisPool == null) {
println("开辟一个连接池")
val config: Properties = PropertiesUtil.load("config.properties")
val host: String = config.getProperty("redis.host")
val port: String = config.getProperty("redis.port")
val jedisPoolConfig = new JedisPoolConfig()
jedisPoolConfig.setMaxTotal(100)
jedisPoolConfig.setMaxIdle(20)
jedisPoolConfig.setMinIdle(20)
jedisPoolConfig.setBlockWhenExhausted(true)
jedisPoolConfig.setMaxWaitMillis(500)
jedisPoolConfig.setTestOnBorrow(true)
jedisPool = new JedisPool(jedisPoolConfig, host, port.toInt)
}
println(s"jedisPool.getNumActive = ${jedisPool.getNumActive}")
println("获得一个连接")
jedisPool.getResource
}
}