Flink写入mysql其实也很简单,只用继承RichSinkFunction这个类,重写里面的方法就行了.具体的实现如下:
/**
* 把结果保存到mysql里面
*/
class MySQLSink extends RichSinkFunction[List[ItemViewCount]] with Serializable {
var connection: sql.Connection = _
var ps: sql.PreparedStatement = _
var statement: java.sql.Statement = _
val username = "***"
val password = "***"
val drivername = "com.mysql.jdbc.Driver"
val url = "***"
/**
* 打开mysql的连接
* @param parameters
*/
override def open(parameters: Configuration): Unit = {
Class.forName(drivername)
connection = DriverManager.getConnection(url, username, password)
statement = connection.createStatement
connection.setAutoCommit(false)
}
/**
* 处理数据后写入mysql
* @param value
*/
override def invoke(value: List[ItemViewCount]): Unit = {
val sql = "insert into topn(itemid,viewcount)