org.springframework.data.mongodb.MongoDbFactory Java Examples

The following examples show how to use org.springframework.data.mongodb.MongoDbFactory. 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: BeihuMongoDataAutoConfiguration.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(MongoDbFactory.class)
public MongoDbFactorySupport<?> mongoDbFactory(ObjectProvider<MongoClient> mongo,
		ObjectProvider<com.mongodb.client.MongoClient> mongoClient) {
	MongoClient preferredClient = mongo.getIfAvailable();
	if (preferredClient != null) {
		return new SimpleMongoDbFactory(preferredClient,
				this.beihuMongoProperties.getMongoClientDatabase());
	}
	com.mongodb.client.MongoClient fallbackClient = mongoClient.getIfAvailable();
	if (fallbackClient != null) {
		return new SimpleMongoClientDbFactory(fallbackClient,
				this.beihuMongoProperties.getMongoClientDatabase());
	}
	throw new IllegalStateException("Expected to find at least one MongoDB client.");
}
 
Example #2
Source File: AbstractCloudConfigServiceScanTest.java    From spring-cloud-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void cloudScanWithAllTypesOfServices() {
	ApplicationContext testContext = getTestApplicationContext(createMysqlService("mysqlDb"), 
															  createPostgresqlService("postDb"),
															  createMongoService("mongoDb"),
															  createRedisService("redisDb"),
															  createRabbitService("rabbit"));
	
	assertNotNull("Getting service by id", testContext.getBean("mysqlDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mysqlDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("postDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("postDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("mongoDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mongoDb", MongoDbFactory.class));		
	
	assertNotNull("Getting service by id", testContext.getBean("redisDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("redisDb", RedisConnectionFactory.class));		

	assertNotNull("Getting service by id", testContext.getBean("rabbit"));
	assertNotNull("Getting service by id and type", testContext.getBean("rabbit", ConnectionFactory.class));		
}
 
Example #3
Source File: MongoConfiguation.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Bean
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, SequenceOption sequenceOption) {
	DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);

	MongoCustomConversions conversions = new MongoCustomConversions(resolverConverter());
	MongoMappingContext mappingContext = new BHBMongoMappingContext();
	mappingContext.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
	mappingContext.afterPropertiesSet();
	MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mappingContext);
	// _class 剔除
	converter.setTypeMapper(new DefaultMongoTypeMapper(null));
	converter.setCustomConversions(conversions);
	converter.afterPropertiesSet();

	// 需要自增时
	// MongoTemplate template=new DTXDMongoTemplate(mongoDbFactory,converter,
	// sequenceOption);
	MongoTemplate template = new MongoTemplate(mongoDbFactory, converter);
	return template;
}
 
Example #4
Source File: SpringMongoDbFactoryBeanPostProcessor.java    From javamelody with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
	if (MONGO_DB_FACTORY_AVAILABLE && bean instanceof MongoDbFactory) {
		final MongoDbFactory mongoDbFactory = (MongoDbFactory) bean;
		final InvocationHandler invocationHandler = new InvocationHandler() {
			/** {@inheritDoc} */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Object result = method.invoke(mongoDbFactory, args);
				if (result instanceof MongoDatabase) {
					result = MongoWrapper.createDatabaseProxy((MongoDatabase) result);
				}
				return result;
			}
		};
		final MongoDbFactory factory = JdbcWrapper.createProxy(mongoDbFactory,
				invocationHandler);
		LOG.debug("mongodb monitoring initialized");
		return factory;
	}

	return bean;
}
 
Example #5
Source File: TestSpringMongoDbFactoryBeanPostProcessor.java    From javamelody with Apache License 2.0 6 votes vote down vote up
/** Test. */
@Test
public void testSpringAOP() {
	final Counter servicesCounter = MonitoringProxy.getServicesCounter();
	servicesCounter.clear();
	final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
			MONITORING_CONTEXT_FILENAME, TEST_CONTEXT_FILENAME);
	try {
		final MongoDbFactory mongoDbFactory = context.getBean(MongoDbFactory.class);
		assertNotNull("toString", mongoDbFactory.toString());
		assertNotNull("getDb", mongoDbFactory.getDb());

		final SpringMongoDbFactoryBeanPostProcessor springMongoDbFactoryBeanPostProcessor = context
				.getBean(SpringMongoDbFactoryBeanPostProcessor.class);
		assertEquals("order", Ordered.LOWEST_PRECEDENCE,
				springMongoDbFactoryBeanPostProcessor.getOrder());
		springMongoDbFactoryBeanPostProcessor.setOrder(1);
		assertEquals("order", 1, springMongoDbFactoryBeanPostProcessor.getOrder());
	} finally {
		context.close();
	}
}
 
Example #6
Source File: MongoServiceConnectorCreatorTest.java    From spring-cloud-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void cloudMongoCreationNoConfig() throws Exception {
	MongoServiceInfo serviceInfo = new MongoServiceInfo("id", TEST_HOST, TEST_PORT, TEST_USERNAME, TEST_PASSWORD, TEST_DB);

	MongoDbFactory mongoDbFactory = testCreator.create(serviceInfo, null);
	assertNotNull(mongoDbFactory);

	MongoClient mongoClient = getMongoClientField(mongoDbFactory);

	MongoCredential credentials = mongoClient.getCredentialsList().get(0);

	List<ServerAddress> addresses = extractServerAddresses(mongoClient);
	assertEquals(1, addresses.size());

	ServerAddress address = addresses.get(0);

	assertEquals(serviceInfo.getHost(), address.getHost());
	assertEquals(serviceInfo.getPort(), address.getPort());
	assertEquals(serviceInfo.getUserName(), credentials.getUserName());
	assertNotNull(credentials.getPassword());

	// Don't do connector.getDatabase().getName() as that will try to initiate the connection
	assertEquals(serviceInfo.getDatabase(), ReflectionTestUtils.getField(mongoDbFactory, "databaseName"));
}
 
Example #7
Source File: MongoConfig.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
public MongoDbFactory mongoDbFactory(MongoClientOptionProperties properties) {
    //创建客户端参数
    MongoClientOptions options = mongoClientOptions(properties);

    //创建客户端和Factory
    List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String address : properties.getAddress()) {
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);
    }

    //创建认证客户端
    MongoCredential mongoCredential = MongoCredential
            .createScramSha1Credential(
                    properties.getUsername(),
                    properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                    properties.getPassword().toCharArray()
            );
    MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, options);

    return new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
}
 
Example #8
Source File: HomeController.java    From hello-spring-cloud with Apache License 2.0 5 votes vote down vote up
private String toString(MongoDbFactory mongoDbFactory) {
    if (mongoDbFactory == null) {
        return "<none>";
    } else {
        try {
            return mongoDbFactory.getDb().getMongo().getAddress().toString();
        } catch (Exception ex) {
            return "<invalid address> " + mongoDbFactory.getDb().getMongo().toString();
        }
    }
}
 
Example #9
Source File: BeihuMongoDataAutoConfiguration.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory,
		MongoTemplate mongoTemplate) {
	return new GridFsTemplate(
			new GridFsMongoDbFactory(mongoDbFactory, this.beihuMongoProperties),
			mongoTemplate.getConverter());
}
 
Example #10
Source File: MongoDbFactoryCloudConfigTestHelper.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
public static void assertConfigProperties(MongoDbFactory connector, String writeConcern, Integer connectionsPerHost, Integer maxWaitTime) {
	if (connectionsPerHost == null) {
		connectionsPerHost = 100; // default
	}
	if (maxWaitTime == null) {
		maxWaitTime = 120000; // default
	}
	assertNotNull(connector);

	assertEquals(ReflectionTestUtils.getField(connector,  "writeConcern"), writeConcern == null ? null : WriteConcern.valueOf(writeConcern));
	
	MongoClient mongoClient = (MongoClient) ReflectionTestUtils.getField(connector, "mongoClient");
	assertEquals(connectionsPerHost.intValue(), mongoClient.getMongoClientOptions().getConnectionsPerHost());
	assertEquals(maxWaitTime.intValue(), mongoClient.getMongoClientOptions().getMaxWaitTime());
}
 
Example #11
Source File: MongoConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoTemplate mongoTemplate(
        MongoClientOptionProperties properties,
        MongoDbFactory factory,
        MongoMappingContext context,
        MongoCustomConversions conversions
) {
    return new MongoTemplate(mongoDbFactory(properties), mappingMongoConverter(factory, context, conversions));
}
 
Example #12
Source File: MongoConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
public MappingMongoConverter mappingMongoConverter(
        MongoDbFactory factory,
        MongoMappingContext context,
        MongoCustomConversions conversions
) {
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
    MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
    mappingConverter.setCustomConversions(conversions);
    mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
    return mappingConverter;
}
 
Example #13
Source File: CloudAllServicesTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void allServicesProvisioned() {
	ApplicationContext testContext = getTestApplicationContext("cloud-all-services.xml", 
															   createMysqlService("mysqlDb"), 
															   createPostgresqlService("postDb"),
															   createMongoService("mongoDb"),
															   createRedisService("redisDb"),
															   createRabbitService("rabbit"),
															   createCassandraService("cassandra"));
	
	assertNotNull("Getting service by id", testContext.getBean("mysqlDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mysqlDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("postDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("postDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("mongoDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mongoDb", MongoDbFactory.class));		
	
	assertNotNull("Getting service by id", testContext.getBean("redisDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("redisDb", RedisConnectionFactory.class));		

	assertNotNull("Getting service by id", testContext.getBean("rabbit"));
	assertNotNull("Getting service by id and type", testContext.getBean("rabbit", ConnectionFactory.class));

	assertNotNull("Getting service by id", testContext.getBean("cassandra"));
		assertNotNull("Getting service by id and type", testContext.getBean("cassandra", Cluster.class));
}
 
Example #14
Source File: $ Spring Data MongoDB Setup.java    From allegro-intellij-templates with Apache License 2.0 5 votes vote down vote up
@Bean(name = "mongoTemplate")
public MongoTemplate createMongoTemplate() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(host, port);
    //TODO Configure additional MongoDB mongoClient settings if needed
    MongoDbFactory factory = new SimpleMongoDbFactory(mongoClient, database, new UserCredentials(username, password));
    MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), new MongoMappingContext());
    converter.setTypeMapper(new DefaultMongoTypeMapper(null));

    return new MongoTemplate(factory, converter);
}
 
Example #15
Source File: AxonMongoTemplate.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@Autowired
public AxonMongoTemplate(MongoDbFactory mongoDbFactory) {
    this.mongoDbFactory = mongoDbFactory;
    this.mongoTemplate = new org.springframework.data.mongodb.core.MongoTemplate(mongoDbFactory);

    domainEventsCollectionName = DEFAULT_DOMAINEVENTS_COLLECTION;
    snapshotEventsCollectionName = DEFAULT_SNAPSHOTEVENTS_COLLECTION;
}
 
Example #16
Source File: BeihuMongoDataAutoConfiguration.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(MongoConverter.class)
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
		MongoMappingContext context, MongoCustomConversions conversions) {
	DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
	MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver,
			context);
	// 去掉 _class项
	mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
	mappingConverter.setCustomConversions(conversions);
	return mappingConverter;
}
 
Example #17
Source File: MongoLocalConfig.java    From spring-music with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoDbFactory mongoDbFactory() {
    try {
        return new SimpleMongoDbFactory(new MongoClient(), "music");
    } catch (UnknownHostException e) {
        throw new RuntimeException("Error creating MongoDbFactory: " + e);
    }
}
 
Example #18
Source File: MongoServiceConnectorCreatorTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void cloudMongoCreationWithMultipleHostsByUri() throws Exception {
	String uri = String.format("%s://%s:%s@%s:%s/%s", MONGODB_SCHEME, TEST_USERNAME, TEST_PASSWORD,
			StringUtils.arrayToDelimitedString(TEST_HOSTS, ","), TEST_PORT, TEST_DB);

	MongoServiceInfo serviceInfo = new MongoServiceInfo("id", uri);

	MongoDbFactory mongoDbFactory = testCreator.create(serviceInfo, null);
	assertNotNull(mongoDbFactory);

	MongoClient mongoClient = getMongoClientField(mongoDbFactory);

	List<ServerAddress> addresses = extractServerAddresses(mongoClient);
	assertEquals(3, addresses.size());

	MongoCredential credentials = mongoClient.getCredentialsList().get(0);
	assertEquals(TEST_USERNAME, credentials.getUserName());
	assertNotNull(credentials.getPassword());

	// Don't do connector.getDatabase().getName() as that will try to initiate the connection
	assertEquals(TEST_DB, ReflectionTestUtils.getField(mongoDbFactory, "databaseName"));

	ServerAddress address1 = addresses.get(0);
	assertEquals(TEST_HOST, address1.getHost());
	assertEquals(TEST_PORT_DEFAULT, address1.getPort());

	ServerAddress address2 = addresses.get(1);
	assertEquals(TEST_HOST_1, address2.getHost());
	assertEquals(TEST_PORT_DEFAULT, address2.getPort());

	ServerAddress address3 = addresses.get(2);
	assertEquals(TEST_HOST_2, address3.getHost());
	assertEquals(TEST_PORT, address3.getPort());
}
 
Example #19
Source File: MongoDbFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigAllOptionsSpecifiedWriteConcernNone() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWait200_WriteConcernNone", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, "none", 50, 200);
}
 
Example #20
Source File: MongoDbFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigAllOptionsSpecifiedWriteConcernSafe() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWait200_WriteConcernSafe", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, "safe", 50, 200);
}
 
Example #21
Source File: MongoDbFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigAllOptionsSpecifiedWriteConcernUnspecified() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWait200_WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, 200);
}
 
Example #22
Source File: MongoDbFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigOnlyConnectionPerHostSpecified() {
	ApplicationContext testContext = 
			getTestApplicationContext(MongoDbFactoryConfigWithServiceConfig.class, createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("connectionPerHost50_MaxWaitUnspecified_WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, 120000);
}
 
Example #23
Source File: MongoDbFactoryXmlConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigAllOptionsSpecifiedWriteConcernNone() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-connectionPerHost50-maxWait200-WriteConcernNone", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, "none", 50, 200);
}
 
Example #24
Source File: MongoDbFactoryXmlConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigOnlyMaxWaitSpecified() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-maxWait200-connectionPerHostUnspecified-WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, null, 200);
}
 
Example #25
Source File: MongoDbFactoryXmlConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigAllOptionsSpecifiedWriteConcernUnspecified() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-maxWait200-connectionPerHost50-WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, 200);
}
 
Example #26
Source File: MongoDbFactoryXmlConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void withConfigOnlyConnectionPerHostSpecified() {
	ApplicationContext testContext = getTestApplicationContext("cloud-mongo-with-config.xml", createService("my-service"));
	
	MongoDbFactory connector = testContext.getBean("service-maxWaitUnspecified-connectionPerHost50-WriteConcernUnspecified", getConnectorType());
	MongoDbFactoryCloudConfigTestHelper.assertConfigProperties(connector, null, 50, null);
}
 
Example #27
Source File: MongoDBConfig.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Bean
public MongoDbFactory mongoDb() throws Exception {
	return new SimpleMongoDbFactory(new MongoClient(MONGO_HOST, MONGO_PORT), DB_NAME);
}
 
Example #28
Source File: MongoDbFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 4 votes vote down vote up
protected Class<MongoDbFactory> getConnectorType() {
	return MongoDbFactory.class;
}
 
Example #29
Source File: CloudDatabaseConfiguration.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 4 votes vote down vote up
@Bean
public MongoDbFactory mongoFactory() {
    return connectionFactory().mongoDbFactory();
}
 
Example #30
Source File: AppConfig.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Bean
public MongoDbFactory mongoDb() throws Exception {
    return new SimpleMongoDbFactory(new MongoClient(MONGO_HOST, MONGO_PORT), DB_NAME);
}