本文整理匯總了Java中com.mongodb.ServerAddress類的典型用法代碼示例。如果您正苦於以下問題:Java ServerAddress類的具體用法?Java ServerAddress怎麽用?Java ServerAddress使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ServerAddress類屬於com.mongodb包,在下文中一共展示了ServerAddress類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: uploadData
import com.mongodb.ServerAddress; //導入依賴的package包/類
public DataAddress uploadData(String data, DataAddress dataAddress) throws UnknownHostException {
ServerAddress server = new ServerAddress(dataAddress.hostname, dataAddress.port);
GridFS database = connectToDatabase(server);
logger.info("Database connected");
GridFSInputFile file = database.createFile(data.getBytes());
int newID = getNextId(database);
logger.info("Got new id for uploaded file: " + newID);
file.setFilename(String.valueOf(newID));
file.put("_id", newID);
file.save();
logger.info("after save");
return new DataAddress(dataAddress.hostname, dataAddress.port, newID);
}
示例2: buildMongoClientFactoryBean
import com.mongodb.ServerAddress; //導入依賴的package包/類
/**
* 生成mongoClientFacotryBean
*
* @param mythMongoConfig 配置信息
* @return bean
*/
private MongoClientFactoryBean buildMongoClientFactoryBean(MythMongoConfig mythMongoConfig) {
MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
MongoCredential credential = MongoCredential.createScramSha1Credential(mythMongoConfig.getMongoUserName(),
mythMongoConfig.getMongoDbName(),
mythMongoConfig.getMongoUserPwd().toCharArray());
clientFactoryBean.setCredentials(new MongoCredential[]{
credential
});
List<String> urls = Splitter.on(",").trimResults().splitToList(mythMongoConfig.getMongoDbUrl());
final ServerAddress[] sds = urls.stream().map(url -> {
List<String> adds = Splitter.on(":").trimResults().splitToList(url);
InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
return new ServerAddress(address);
}).collect(Collectors.toList()).toArray(new ServerAddress[]{});
clientFactoryBean.setReplicaSetSeeds(sds);
return clientFactoryBean;
}
示例3: setup
import com.mongodb.ServerAddress; //導入依賴的package包/類
private static void setup() throws UnknownHostException, IOException {
IMongoCmdOptions cmdOptions = new MongoCmdOptionsBuilder().verbose(false)
.enableAuth(authEnabled).build();
IMongodConfig mongodConfig = new MongodConfigBuilder()
.version(Version.Main.PRODUCTION)
.net(new Net(LOCALHOST, MONGOS_PORT, Network.localhostIsIPv6()))
.cmdOptions(cmdOptions).build();
IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(
Command.MongoD).build();
mongodExecutable = MongodStarter.getInstance(runtimeConfig).prepare(
mongodConfig);
mongod = mongodExecutable.start();
mongoClient = new MongoClient(new ServerAddress(LOCALHOST, MONGOS_PORT));
createDbAndCollections(EMPLOYEE_DB, EMPINFO_COLLECTION, "employee_id");
createDbAndCollections(EMPLOYEE_DB, SCHEMA_CHANGE_COLLECTION, "field_2");
}
示例4: connectToDatabaseCluster
import com.mongodb.ServerAddress; //導入依賴的package包/類
public boolean connectToDatabaseCluster(final List<String> seeds) {
try {
List<ServerAddress> seedList = new ArrayList<>();
for (String ip : seeds) {
seedList.add(new ServerAddress(ip, MONGO_PORT));
}
mongoClient = new MongoClient(seedList);
mongoDatabase = mongoClient.getDatabase("featureStore");
dbCollectionList = getCollectionList(mongoDatabase);
log.info("Connect to database cluster successfully!!");
return true;
} catch (Exception e) {
log.warn(e.getMessage());
return false;
}
}
示例5: main
import com.mongodb.ServerAddress; //導入依賴的package包/類
public static void main(String[] args) {
MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder().codecRegistry(getCodecRegistry()).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), mongoClientOptions);
MongoDatabase database = mongoClient.getDatabase("tutorial");
MongoCollection<PolymorphicPojo> collection = database.getCollection("entities").withDocumentClass(PolymorphicPojo.class);
// create some pojo
Pojo pojo = new Pojo();
pojo.setName("A nice name");
pojo.setPojos(Arrays.asList(new SubPojo(42), new SubPojo(48)));
// insert into db
collection.insertOne(pojo);
// read from db
PolymorphicPojo foundPojo = collection.find(Filters.eq("_id", pojo.getId())).first();
// output
LOGGER.debug("Found pojo {}", foundPojo);
}
示例6: buildMongoClientFactoryBean
import com.mongodb.ServerAddress; //導入依賴的package包/類
/**
* 生成mongoClientFacotryBean
*
* @param config 配置信息
* @return bean
*/
private MongoClientFactoryBean buildMongoClientFactoryBean(TxMongoConfig config) {
MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
MongoCredential credential = MongoCredential.createScramSha1Credential(config.getMongoUserName(),
config.getMongoDbName(),
config.getMongoUserPwd().toCharArray());
clientFactoryBean.setCredentials(new MongoCredential[]{
credential
});
List<String> urls = Splitter.on(",").trimResults().splitToList(config.getMongoDbUrl());
final ServerAddress[] serverAddresses = urls.stream().filter(Objects::nonNull)
.map(url -> {
List<String> adds = Splitter.on(":").trimResults().splitToList(url);
return new ServerAddress(adds.get(0), Integer.valueOf(adds.get(1)));
}).collect(Collectors.toList()).toArray(new ServerAddress[urls.size()]);
clientFactoryBean.setReplicaSetSeeds(serverAddresses);
return clientFactoryBean;
}
示例7: check
import com.mongodb.ServerAddress; //導入依賴的package包/類
/**
* Check that we can talk to the configured MongoDB instance.
*
* @return a {@link Result} with details of whether this check was successful or not
* @throws Exception not thrown, any failure to perform the check results in a failed {@link
* Result}
*/
@Override
protected Result check() throws Exception {
MongoClient mongoClient = mongoProvider.provide();
List<ServerAddress> serverAddresses = mongoClient.getSettings().getClusterSettings().getHosts();
String address =
serverAddresses.stream().map(ServerAddress::toString).collect(Collectors.joining(","));
try {
// any read will suffice to prove connectivity
mongoClient.getDatabase("xyz");
return Result.healthy("Connected to MongoDB at " + address);
} catch (Exception ex) {
return Result.unhealthy("Cannot connect to MongoDB at " + address);
}
}
示例8: beforeTest
import com.mongodb.ServerAddress; //導入依賴的package包/類
@Override
public void beforeTest() {
final MongoCredential credential =
MongoCredential.createCredential("bench", "benchmark", "bench".toCharArray());
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
mongoClient = new MongoClient(serverAddress, new ArrayList<MongoCredential>() {{ add(credential); }});
db = mongoClient.getDatabase("benchmark");
Person[] personList = testHelper.loadData();
documents = new ArrayList<>();
ObjectMapper objectMapper = new ObjectMapper();
for (Person person : personList) {
StringWriter writer = new StringWriter();
try {
objectMapper.writeValue(writer, person);
Document document = Document.parse(writer.toString());
documents.add(document);
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例9: buildMongoClientFactoryBean
import com.mongodb.ServerAddress; //導入依賴的package包/類
/**
* 生成mongoClientFacotryBean
*
* @param tccMongoConfig 配置信息
* @return bean
*/
private MongoClientFactoryBean buildMongoClientFactoryBean(TccMongoConfig tccMongoConfig) {
MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
MongoCredential credential = MongoCredential.createScramSha1Credential(tccMongoConfig.getMongoUserName(),
tccMongoConfig.getMongoDbName(),
tccMongoConfig.getMongoUserPwd().toCharArray());
clientFactoryBean.setCredentials(new MongoCredential[]{
credential
});
List<String> urls = Splitter.on(",").trimResults().splitToList(tccMongoConfig.getMongoDbUrl());
ServerAddress[] sds = new ServerAddress[urls.size()];
for (int i = 0; i < sds.length; i++) {
List<String> adds = Splitter.on(":").trimResults().splitToList(urls.get(i));
InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
sds[i] = new ServerAddress(address);
}
clientFactoryBean.setReplicaSetSeeds(sds);
return clientFactoryBean;
}
示例10: setup
import com.mongodb.ServerAddress; //導入依賴的package包/類
/** The mongodb ops. */
/* (non-Javadoc)
* @see co.aurasphere.botmill.core.datastore.adapter.DataAdapter#setup()
*/
public void setup() {
MongoCredential credential = MongoCredential.createCredential(
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.username"),
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"),
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.password").toCharArray());
ServerAddress serverAddress = new ServerAddress(
ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.server"),
Integer.valueOf(ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.port")));
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongoClient, ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"));
MongoTemplate mongoTemplate = new MongoTemplate(simpleMongoDbFactory);
this.source = (MongoOperations) mongoTemplate;
}
示例11: uriConstructedSuccessfullyWithMultipleServerAddresses
import com.mongodb.ServerAddress; //導入依賴的package包/類
@Test
public void uriConstructedSuccessfullyWithMultipleServerAddresses() {
String expected = "mongodb://username:[email protected]:1,server2:2/database";
List<ServerAddress> addresses = new ArrayList<ServerAddress>();
addresses.add(server1);
addresses.add(server2);
when(server1.getHost()).thenReturn("server1");
when(server1.getPort()).thenReturn(1);
when(server2.getHost()).thenReturn("server2");
when(server2.getPort()).thenReturn(2);
when(client.getAllAddress()).thenReturn(addresses);
assertEquals(expected, service.getConnectionString("database", "username", "password"));
}
示例12: init
import com.mongodb.ServerAddress; //導入依賴的package包/類
@SuppressWarnings("deprecation")
public void init() {
String[] list = server.split(":");
String host = list[0];
int port = Integer.parseInt(list[1]);
int connectTimeout = 1000 * 60;
MongoClientOptions options = new MongoClientOptions.Builder().connectTimeout(connectTimeout).build();
client = new MongoClient(new ServerAddress(host, port), options);
this.db = client.getDB(this.database);
if (username != null && username.length() > 0) {
if (password != null && password.length() > 0) {
db.addUser(username, password.toCharArray());
}
}
this.collection = db.getCollection(collectionName);
}
示例13: MongoAuditConfig
import com.mongodb.ServerAddress; //導入依賴的package包/類
public MongoAuditConfig() {
Map<String, Object> defaultMap = new HashMap<>();
defaultMap.put("mongoAudit.hostname", "localhost");
defaultMap.put("mongoAudit.port", 27017);
defaultMap.put("mongoAudit.username", "");
defaultMap.put("mongoAudit.password", "");
Config defaultConf = ConfigFactory.parseMap(defaultMap);
Config config = ConfigFactory.load().withFallback(defaultConf);
setPort(config.getInt("mongoAudit.port"));
setUsername(config.getString("mongoAudit.username"));
setPassword(config.getString("mongoAudit.password"));
List<String> seedList = Optional.ofNullable(config.getString("mongoAudit.hostname")).isPresent() ?
Arrays.asList(config.getString("mongoAudit.hostname").split(",")) : null;
for (String seed : seedList) {
try {
hostname.add(new ServerAddress(seed, port));
} catch (Exception e) {
LOG.error("Error constructing mongo factory", e);
}
}
}
示例14: MongoBillingConfig
import com.mongodb.ServerAddress; //導入依賴的package包/類
public MongoBillingConfig() {
Map<String, Object> defaultMap = new HashMap<>();
defaultMap.put("mongoBilling.hostname", "localhost");
defaultMap.put("mongoBilling.port", 27017);
defaultMap.put("mongoBilling.username", "");
defaultMap.put("mongoBilling.password", "");
Config defaultConf = ConfigFactory.parseMap(defaultMap);
Config config = ConfigFactory.load().withFallback(defaultConf);
setPort(config.getInt("mongoBilling.port"));
setUsername(config.getString("mongoBilling.username"));
setPassword(config.getString("mongoBilling.password"));
List<String> seedList = Optional.ofNullable(config.getString("mongoBilling.hostname")).isPresent() ?
Arrays.asList(config.getString("mongoBilling.hostname").split(",")) : null;
for (String seed : seedList) {
try {
hostname.add(new ServerAddress(seed, port));
} catch (Exception e) {
LOG.error("Error constructing mongo factory", e);
}
}
}
示例15: init
import com.mongodb.ServerAddress; //導入依賴的package包/類
@Override
public void init() {
MongoCredential credential = null;
if (!Strings.isNullOrEmpty(this.configuration.getUsername())) {
credential = MongoCredential.createCredential(
this.configuration.getUsername(),
this.configuration.getDatabase(),
Strings.isNullOrEmpty(this.configuration.getPassword()) ? null : this.configuration.getPassword().toCharArray()
);
}
String[] addressSplit = this.configuration.getAddress().split(":");
String host = addressSplit[0];
int port = addressSplit.length > 1 ? Integer.parseInt(addressSplit[1]) : 27017;
ServerAddress address = new ServerAddress(host, port);
if (credential == null) {
this.mongoClient = new MongoClient(address, Collections.emptyList());
} else {
this.mongoClient = new MongoClient(address, Collections.singletonList(credential));
}
this.database = this.mongoClient.getDatabase(this.configuration.getDatabase());
}