Spring整合MongoTemplate
2017-09-25 本文已影响16人
H_Man
xml形式的整合
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mongo" />
<!-- 获取配置资源 -->
<context:property-placeholder location="classpath:mongodb-context-config.properties" />
<mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" >
<mongo:options
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
auto-connect-retry="${mongo.autoConnectRetry}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
slave-ok="${mongo.slaveOk}"
write-number="1"
write-timeout="0" write-fsync="true"/>
</mongo:mongo>
<!-- 设置使用的数据库 名-->
<mongo:db-factory dbname="test" mongo-ref="mongo"/>
<!-- mongodb的模板 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
</beans>
由于公司用的是dubbo容器,所以需要使用代码的方式实现(类似于springboot)
String host ="your host";
Integer port = "your port";
String username = "username";
String defaultDataBaseName = "default database name";
String password = "password";
//address
ServerAddress address = new ServerAddress(host, port);
//client
MongoCredential mongoCredential = MongoCredential.createCredential(username, defaultDataBaseName, password.toCharArray());
LinkedList<MongoCredential> mongoCredentials = Lists.newLinkedList();
mongoCredentials.add(mongoCredential);
MongoClient client = new MongoClient(address, mongoCredentials);
client.setWriteConcern(WriteConcern.SAFE);
//factory
SimpleMongoDbFactory factory = new SimpleMongoDbFactory(client, defaultDataBaseName);
//template
MongoTemplate template = new MongoTemplate(factory);
mongoTemplate = template;
以上代码只要在容器加载的时候,执行一遍, 就可以实现了.