MeterSphere 基于目前数据库驱动只能支持如下类型数据库,所有如果去连接 Redis 和 MongoDB 数据库,只能通过自定义脚本的方式去实现。

Redis

连接数据库并查询 key 值:

mport redis.clients.jedis.Jedis;
import org.apache.commons.lang3.StringUtils;
String host = "10.1.12.*";  //服务器地址
int port = 6379;  //端口号
int index = 0;  //redis db
String key = "runoobkey";  //key值
Jedis jedis = new Jedis(host, port);
jedis.select(index);
String redisGetResult = jedis.get(key);
vars.put("redisGetResult",redisGetResult);  //将key值保存为变量
log.info("runoobkey:"+(vars.get("redisGetResult")));

效果如下:

MongoDB

连接数据库并查询 collection id

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.\*;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.bson.Document;
import java.util.Arrays;
try {
    MongoClient mongoClient = MongoClients.create("mongodb://10.1.12.124:27017/?authSource=admin");
    MongoDatabase database = mongoClient.getDatabase(vars.get("databaseName"));
    MongoCollection<Document> collection = database.getCollection(vars.get("collectionName"));
    vars.putObject("collection", collection);
    Document result = collection.find().first();
    String resultStr = result.get("_id").toString();
    String resultJson = result.toJson();
    return resultStr;
}
catch (Exception e) {
SampleResult.setSuccessful(false);
SampleResult.setResponseCode("500");
SampleResult.setResponseMessage("Exception: " + e);
}

效果如下:

注意:脚本语言为 groovy。


↙↙↙阅读原文可查看相关链接,并与作者交流