序
本文主要研究一下flink的ParameterTool
实例
fromPropertiesFile
String propertiesFilePath = "/home/sam/flink/myjob.properties";
ParameterTool parameter = ParameterTool.fromPropertiesFile(propertiesFilePath);
File propertiesFile = new File(propertiesFilePath);
ParameterTool parameter = ParameterTool.fromPropertiesFile(propertiesFile);
InputStream propertiesFileInputStream = new FileInputStream(file);
ParameterTool parameter = ParameterTool.fromPropertiesFile(propertiesFileInputStream);
- 使用ParameterTool.fromPropertiesFile从.properties文件创建ParameterTool
fromArgs
public static void main(String[] args) {
ParameterTool parameter = ParameterTool.fromArgs(args);
// .. regular code ..
}
- 使用ParameterTool.fromArgs从命令行创建ParameterTool(
比如--input hdfs:///mydata --elements 42
)
fromSystemProperties
ParameterTool parameter = ParameterTool.fromSystemProperties();
- 使用ParameterTool.fromSystemProperties从system properties创建ParameterTool(
比如-Dinput=hdfs:///mydata
)
获取参数值
ParameterTool parameters = // ...
parameter.getRequired("input");
parameter.get("output", "myDefaultValue");
parameter.getLong("expectedCount", -1L);
parameter.getNumberOfParameters()
// .. there are more methods available.
- 可以使用ParameterTool的get、getRequired、getLong等方法获取参数值
设置为global
env.getConfig().setGlobalJobParameters(parameters);
public static final class Tokenizer extends RichFlatMapFunction<String, Tuple2<String, Integer>> {
@Override
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
ParameterTool parameters = (ParameterTool)
getRuntimeContext().getExecutionConfig().getGlobalJobParameters();
parameters.getRequired("input");
// ... do more ...
}
- 使用env.getConfig().setGlobalJobParameters将ParameterTool的访问范围设置为global
GlobalJobParameters
flink-core-1.7.1-sources.jar!/org/apache/flink/api/common/ExecutionConfig.java
public static class GlobalJobParameters implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Convert UserConfig into a {@code Map<String, String>} representation.
* This can be used by the runtime, for example for presenting the user config in the web frontend.
*
* @return Key/Value representation of the UserConfig
*/
public Map<String, String> toMap() {
return Collections.emptyMap();
}
}
- GlobalJobParameters里头有一个toMap方法,返回Collections.emptyMap()
ParameterTool
flink-java-1.7.1-sources.jar!/org/apache/flink/api/java/utils/ParameterTool.java
@Public
public class ParameterTool extends ExecutionConfig.GlobalJobParameters implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
protected static final String NO_VALUE_KEY = "__NO_VALUE_KEY";
protected static final String DEFAULT_UNDEFINED = "<undefined>";
//......
// -------