package org.springblade.sink.mongodb;

import cn.hutool.db.nosql.mongo.MongoFactory;
import com.ldt.entity.alarm.IPAlarm;
import com.mongodb.client.MongoDatabase;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.bson.Document;
import org.springblade.utils.MongoUtils;


/**
 * @author: lianghanqiang
 * @description:
 * @since: 10/28/21 -- 6:05 PM
 */
public class IPAlarmSink  extends RichSinkFunction<IPAlarm> {

	private MongoDatabase mongoDatabase;

	/**
	 * 链接mongo
	 */
	@Override
	public void open(Configuration parameters) throws Exception {
		this.mongoDatabase = MongoFactory.getDS("master").getDb(MongoUtils.getProperties().get("master","database"));
		super.open(parameters);
	}

	/**
	 * 将数据写入
	 */
	@Override
	public void invoke(IPAlarm value, Context context) {
		System.out.println(value);
		Document document = new Document();
		document.append("ip",value.getIp());
		document.append("eventTime",value.getTimes());
		document.append("frequency",value.getTimes());
		this.mongoDatabase.getCollection("ip_alarm").insertOne(document);
	}

	/**
	 * 释放资源
	 */
	@Override
	public void close() throws Exception {
		super.close();
	}

}
