Java Code Examples for org.influxdb.InfluxDBFactory#connect()

The following examples show how to use org.influxdb.InfluxDBFactory#connect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InfluxDBSink.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
@Override
public void open(Configuration parameters) throws Exception {
    super.open(parameters);

    influxDBClient = InfluxDBFactory.connect(influxDBConfig.getUrl(), influxDBConfig.getUsername(), influxDBConfig.getPassword());

    if (!influxDBClient.databaseExists(influxDBConfig.getDatabase())) {
        if(influxDBConfig.isCreateDatabase()) {
            influxDBClient.createDatabase(influxDBConfig.getDatabase());
        }
        else {
            throw new RuntimeException("This " + influxDBConfig.getDatabase() + " database does not exist!");
        }
    }

    influxDBClient.setDatabase(influxDBConfig.getDatabase());

    if (influxDBConfig.getBatchActions() > 0) {
        influxDBClient.enableBatch(influxDBConfig.getBatchActions(), influxDBConfig.getFlushDuration(), influxDBConfig.getFlushDurationTimeUnit());
    }

    if (influxDBConfig.isEnableGzip()) {
        influxDBClient.enableGzip();
    }
}
 
Example 2
Source File: InfluxdbReporter.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void open(MetricConfig config) {
	String host = getString(config, HOST);
	int port = getInteger(config, PORT);
	if (!isValidHost(host) || !isValidPort(port)) {
		throw new IllegalArgumentException("Invalid host/port configuration. Host: " + host + " Port: " + port);
	}
	String database = getString(config, DB);
	if (database == null) {
		throw new IllegalArgumentException("'" + DB.key() + "' configuration option is not set");
	}
	String url = String.format("http://%s:%d", host, port);
	String username = getString(config, USERNAME);
	String password = getString(config, PASSWORD);

	this.database = database;
	this.retentionPolicy = getString(config, RETENTION_POLICY);
	if (username != null && password != null) {
		influxDB = InfluxDBFactory.connect(url, username, password);
	} else {
		influxDB = InfluxDBFactory.connect(url);
	}

	log.info("Configured InfluxDBReporter with {host:{}, port:{}, db:{}, and retentionPolicy:{}}", host, port, database, retentionPolicy);
}
 
Example 3
Source File: InfluxdbGateway.java    From redis-rdb-cli with Apache License 2.0 6 votes vote down vote up
protected InfluxDB create() {
    //
    final OkHttpClient.Builder http = new OkHttpClient.Builder();
    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequests(2); dispatcher.setMaxRequestsPerHost(2);
    http.dispatcher(dispatcher);
    http.connectionPool(new ConnectionPool(threads, 5, TimeUnit.MINUTES));
    
    //
    final InfluxDB r = InfluxDBFactory.connect(url, user, password, http);
    BatchOptions opt = DEFAULTS;
    opt = opt.consistency(consistency).jitterDuration(jitter);
    opt = opt.actions(this.actions).threadFactory(new XThreadFactory("influxdb"));
    opt = opt.exceptionHandler(new ExceptionHandler()).bufferLimit(capacity).flushDuration(interval);
    r.setDatabase(this.database).setRetentionPolicy(retention).enableBatch((opt)).enableGzip();
    return r;
}
 
Example 4
Source File: InfluxDBConnectionFactory.java    From spring-data-influxdb with Apache License 2.0 6 votes vote down vote up
public InfluxDB getConnection()
{
  Assert.notNull(getProperties(), "InfluxDBProperties are required");
  if (connection == null)
  {
    final Builder client = new OkHttpClient.Builder()
      .connectTimeout(properties.getConnectTimeout(), TimeUnit.SECONDS)
      .writeTimeout(properties.getWriteTimeout(), TimeUnit.SECONDS)
      .readTimeout(properties.getReadTimeout(), TimeUnit.SECONDS);
    connection = InfluxDBFactory
      .connect(properties.getUrl(), properties.getUsername(), properties.getPassword(), client);
    logger.debug("Using InfluxDB '{}' on '{}'", properties.getDatabase(), properties.getUrl());
    if (properties.isGzip())
    {
      logger.debug("Enabled gzip compression for HTTP requests");
      connection.enableGzip();
    }
  }
  return connection;
}
 
Example 5
Source File: OffsetsInfluxDBDaoImpl.java    From Kafka-Insight with Apache License 2.0 5 votes vote down vote up
@Override
    public void insert() {
        InfluxDB influxDB = null;
        try {
            influxDB = InfluxDBFactory.connect(influxDBUrl);
            if (!influxDB.databaseExists(dbName)) {
                influxDB.createDatabase(dbName);
            }
            for (OffsetInfo offsetInfo : offsetInfoList) {
                String group = offsetInfo.getGroup();
                String topic = offsetInfo.getTopic();
                Long logSize = offsetInfo.getLogSize();
                Long offsets = offsetInfo.getCommittedOffset();
                Long lag = offsetInfo.getLag();
                Long timestamp = offsetInfo.getTimestamp();

                BatchPoints batchPoints = BatchPoints
                        .database(dbName)
                        .tag("group", group)
                        .tag("topic", topic)
                        .build();
                Point point = Point.measurement("offsetsConsumer")
                        .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
//                        .time(timestamp, TimeUnit.MILLISECONDS)
                        .addField("logSize", logSize)
                        .addField("offsets", offsets)
                        .addField("lag", lag)
                        .build();
                batchPoints.point(point);
                influxDB.write(batchPoints);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (influxDB != null) {
                influxDB.close();
            }
        }

    }
 
Example 6
Source File: InfluxClient.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void connect() {
    influx = InfluxDBFactory.connect(config.getUrl(), config.getUser(), config.getPassword(),
                                     new OkHttpClient.Builder().readTimeout(3, TimeUnit.MINUTES)
                                                               .writeTimeout(3, TimeUnit.MINUTES),
                                     InfluxDB.ResponseFormat.MSGPACK
    );
    influx.query(new Query("CREATE DATABASE " + database));
    influx.enableGzip();

    influx.enableBatch(config.getActions(), config.getDuration(), TimeUnit.MILLISECONDS);
    influx.setDatabase(database);
}
 
Example 7
Source File: AbstractITInfluxDB.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void initInfluxDB() throws InterruptedException, Exception {
    influxDB = InfluxDBFactory.connect(dbUrl,user,password);
    influxDB.createDatabase(dbName);
    int max = 10;
    while (!influxDB.databaseExists(dbName) && (max-- < 0)) {
        Thread.sleep(5);
    }
    if ( ! influxDB.databaseExists(dbName) ) {
        throw new Exception("unable to create database " + dbName);
    }
}
 
Example 8
Source File: InfluxDBIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    cubeController.create(CONTAINER_INFLUX_DB);
    cubeController.start(CONTAINER_INFLUX_DB);

    InfluxDB influxDB = InfluxDBFactory.connect("http://" + TestUtils.getDockerHost() + ":8086", "admin", "admin");
    influxDB.createDatabase(INFLUX_DB_NAME);
    context.bind(INFLUX_DB_BIND_NAME, influxDB);
}
 
Example 9
Source File: InfluxDBBuilderImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public InfluxDB build(InfluxDBSinkConfig config) {
    InfluxDB influxDB;

    boolean enableAuth = !Strings.isNullOrEmpty(config.getUsername());
    if (enableAuth) {
        log.info("Authenticating to {} as {}", config.getInfluxdbUrl(), config.getUsername());
        influxDB = InfluxDBFactory.connect(config.getInfluxdbUrl(), config.getUsername(), config.getPassword());
    } else {
        log.info("Connecting to {}", config.getInfluxdbUrl());
        influxDB = InfluxDBFactory.connect(config.getInfluxdbUrl());
    }

    if (config.isGzipEnable()) {
        influxDB.enableGzip();
    }

    InfluxDB.LogLevel logLevel;
    try {
        logLevel = InfluxDB.LogLevel.valueOf(config.getLogLevel().toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Illegal Log Level, valid values are: "
            + Arrays.asList(InfluxDB.LogLevel.values()));
    }
    influxDB.setLogLevel(logLevel);

    return influxDB;
}
 
Example 10
Source File: InfluxdbReporter.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void open(MetricConfig config) {
	String host = getString(config, HOST);
	int port = getInteger(config, PORT);
	if (!isValidHost(host) || !NetUtils.isValidClientPort(port)) {
		throw new IllegalArgumentException("Invalid host/port configuration. Host: " + host + " Port: " + port);
	}
	String database = getString(config, DB);
	if (database == null) {
		throw new IllegalArgumentException("'" + DB.key() + "' configuration option is not set");
	}
	String url = String.format("http://%s:%d", host, port);
	String username = getString(config, USERNAME);
	String password = getString(config, PASSWORD);

	this.database = database;
	this.retentionPolicy = getString(config, RETENTION_POLICY);
	this.consistency = getConsistencyLevel(config, CONSISTENCY);

	int connectTimeout = getInteger(config, CONNECT_TIMEOUT);
	int writeTimeout = getInteger(config, WRITE_TIMEOUT);
	OkHttpClient.Builder client = new OkHttpClient.Builder()
		.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
		.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS);

	if (username != null && password != null) {
		influxDB = InfluxDBFactory.connect(url, username, password, client);
	} else {
		influxDB = InfluxDBFactory.connect(url, client);
	}

	log.info("Configured InfluxDBReporter with {host:{}, port:{}, db:{}, retentionPolicy:{} and consistency:{}}",
		host, port, database, retentionPolicy, consistency.name());
}
 
Example 11
Source File: InfluxdbComponent.java    From awacs with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Configuration configuration) throws InitializationException {
    database = configuration.getString(CFG_DATABASE);
    retentionPolicy = configuration.getString(CFG_RETENTION_POLICY, "");
    try {
        consistency = InfluxDB.ConsistencyLevel.valueOf(configuration.getString(CFG_CONSISTENCY_LEVEL));
    } catch (Exception e) {
        consistency = DEFAULT_CONSISTENCY_LEVEL;
    }
    influx = InfluxDBFactory.connect(configuration.getString(CFG_URL),
            configuration.getString(CFG_USERNAME),
            configuration.getString(CFG_PASSWORD));
}
 
Example 12
Source File: JMeterInfluxDBBackendListenerClient.java    From JMeter-InfluxDB-Writer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup influxDB client.
 * 
 * @param context
 *            {@link BackendListenerContext}.
 */
private void setupInfluxClient(BackendListenerContext context) {
	influxDBConfig = new InfluxDBConfig(context);
	influxDB = InfluxDBFactory.connect(influxDBConfig.getInfluxDBURL(), influxDBConfig.getInfluxUser(), influxDBConfig.getInfluxPassword());
	influxDB.enableBatch(100, 5, TimeUnit.SECONDS);
	createDatabaseIfNotExistent();
}
 
Example 13
Source File: InfluxDBPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void connect() {
  if (influxDB == null) {
    // reuse an existing InfluxDB object because it has no state concerning the database
    // connection
    influxDB = InfluxDBFactory.connect(url, user, password);
  }
  connected = true;
}
 
Example 14
Source File: StatsCollector.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates connection to InfluxDB. If the database does not exist, it throws a CloudRuntimeException. </br>
 * @note the user can configure the database name on parameter 'stats.output.influxdb.database.name'; such database must be yet created and configured by the user.
 * The Default name for the database is 'cloudstack_stats'.
 */
protected InfluxDB createInfluxDbConnection() {
    String influxDbQueryUrl = String.format("http://%s:%s/", externalStatsHost, externalStatsPort);
    InfluxDB influxDbConnection = InfluxDBFactory.connect(influxDbQueryUrl);

    if (!influxDbConnection.databaseExists(databaseName)) {
        throw new CloudRuntimeException(String.format("Database with name %s does not exist in influxdb host %s:%s", databaseName, externalStatsHost, externalStatsPort));
    }

    return influxDbConnection;
}
 
Example 15
Source File: InflusDbUtil.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
public static InfluxDB getConnection(){
    if(influxDB == null ){
        synchronized (InflusDbUtil.class){
            influxDB = InfluxDBFactory.connect(HOST_PORT, USER_NAME, PWD);
            influxDB.enableBatch(2000, 100, TimeUnit.MILLISECONDS);
        }
    }
    return influxDB;
}
 
Example 16
Source File: InfluxDBReporter.java    From statsd-jvm-profiler with MIT License 5 votes vote down vote up
/**
 *
 * @param server The server to which to report data
 * @param port The port on which the server is running
 * @param prefix The prefix for metrics
 * @return An InfluxDB client
 */
@Override
protected InfluxDB createClient(String server, int port, String prefix) {
    String url = resolveUrl(server, port);
    logInfo(String.format("Connecting to influxDB at %s", url));

    return InfluxDBFactory.connect(url, username, password);
}
 
Example 17
Source File: InfluxDbTelemetryManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean start(String name) {
    boolean success = false;
    TelemetryConfig config = telemetryConfigService.getConfig(name);
    InfluxDbTelemetryConfig influxDbConfig = fromTelemetryConfig(config);

    if (influxDbConfig != null && !config.name().equals(INFLUXDB_SCHEME) &&
            config.status() == ENABLED) {
        StringBuilder influxDbServerBuilder = new StringBuilder();
        influxDbServerBuilder.append(INFLUX_PROTOCOL);
        influxDbServerBuilder.append(":");
        influxDbServerBuilder.append("//");
        influxDbServerBuilder.append(influxDbConfig.address());
        influxDbServerBuilder.append(":");
        influxDbServerBuilder.append(influxDbConfig.port());

        if (testConnectivity(influxDbConfig.address(), influxDbConfig.port())) {
            InfluxDB producer = InfluxDBFactory.connect(influxDbServerBuilder.toString(),
                    influxDbConfig.username(), influxDbConfig.password());
            producers.put(name, producer);
            createDB(producer, influxDbConfig.database());
            success = true;
        } else {
            log.warn("Unable to connect to {}:{}, " +
                            "please check the connectivity manually",
                            influxDbConfig.address(), influxDbConfig.port());
        }
    }

    return success;
}
 
Example 18
Source File: MBeansInfluxDBDaoImpl.java    From Kafka-Insight with Apache License 2.0 4 votes vote down vote up
@Override
    public void insert() {

        InfluxDB influxDB = null;
        try {
            influxDB = InfluxDBFactory.connect(influxDBUrl);
            if (!influxDB.databaseExists(dbName)) {
                influxDB.createDatabase(dbName);
            }
            for (MBeanInfo mBeanInfo : mBeanInfoList) {
                String label = mBeanInfo.getLabel();
                String topic = mBeanInfo.getTopic();
                double oneMinute = mBeanInfo.getOneMinute();
                double fiveMinute = mBeanInfo.getFiveMinute();
                double fifteenMinute = mBeanInfo.getFifteenMinute();
                double meanRate = mBeanInfo.getMeanRate();


                BatchPoints batchPoints = BatchPoints
                        .database(dbName)
                        .tag("label", label)
                        .tag("topic", topic)
                        .build();
                Point point = Point.measurement("mBeanMetric")
                        .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
//                        .time(timestamp, TimeUnit.MILLISECONDS)
                        .addField("oneMinuteRate", oneMinute)
                        .addField("fiveMinuteRate", fiveMinute)
                        .addField("fifteenMinuteRate", fifteenMinute)
                        .addField("meanRate", meanRate)
                        .build();
                batchPoints.point(point);
                influxDB.write(batchPoints);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (influxDB != null) {
                influxDB.close();
            }
        }

    }
 
Example 19
Source File: InfluxDbAppender.java    From karaf-decanter with Apache License 2.0 4 votes vote down vote up
public void activate(Dictionary<String, Object> config) {
    this.config = config;
    if (config.get("url") == null) {
        throw new IllegalArgumentException("url property is mandatory");
    }
    String url = (String) config.get("url");
    String username = null;
    if (config.get("username") != null) {
        username = (String) config.get("username");
    }
    String password = null;
    if (config.get("password") != null) {
        password = (String) config.get("password");
    }
    if (username != null) {
        this.influxDB = InfluxDBFactory.connect(url, username, password);
    } else {
        this.influxDB = InfluxDBFactory.connect(url);
    }
    String database = "decanter";
    if (config.get("database") != null) {
        database = (String) config.get("database");
    }

    BatchOptions batchOptions = BatchOptions.DEFAULTS;
    if (config.get("batchActionsLimit") != null) {
        int batchActionsLimit = Integer.parseInt((String) config.get("batchActionsLimit"));
        batchOptions = batchOptions.actions(batchActionsLimit);
    }
    if (config.get("precision") != null) {
        TimeUnit timeUnit = TimeUnit.valueOf((String) config.get("precision"));
        batchOptions = batchOptions.precision(timeUnit);
    }

    if (config.get("flushDuration") != null) {
        int flushDuration = Integer.parseInt((String) config.get("flushDuration"));
        batchOptions = batchOptions.flushDuration(flushDuration);
    }

    String prefix = "tag.";
    for (Enumeration<String> e = config.keys(); e.hasMoreElements(); ) {
        String key = e.nextElement();
        if( key.startsWith(prefix)) {
            Object value = this.config.get(key);
            if (value != null)
                globalTags.put(key.substring(4),value.toString());
        }
    }

    this.influxDB.enableBatch(batchOptions);
    this.influxDB.setDatabase(database);
}
 
Example 20
Source File: InfluxDBConnectionLiveTest.java    From tutorials with MIT License 2 votes vote down vote up
private InfluxDB connectDatabase() {

        // Connect to database assumed on localhost with default credentials.
        return  InfluxDBFactory.connect("http://127.0.0.1:8086", "admin", "admin");

    }