springboot:mongodb
程序员文章站
2022-06-16 08:04:46
...
pom.xml
=========================================
<!-- Spring Boot mongodb 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
=========================================
application.properties
=========================================
mongo.host=host
mongo.port=port
mongo.username=username
mongo.password=password
mongo.database=db
mongo.connections-per-host=10
mongo.threads-allowed-to-block-for-connection-multiplier=5
mongo.connect-timeout=60000
mongo.max-wait-time=120000
mongo.auto-connect-retry=true
mongo.socket-keep-alive=false
mongo.socket-timeout=0
=========================================
MongodbConfig.java
=========================================
@Configuration
public class MongodbConfig {
@Value("${mongo.host}")
private String host;
@Value("${mongo.port}")
private int port;
@Value("${mongo.username}")
private String username;
@Value("${mongo.database}")
private String db;
@Value("${mongo.password}")
private char[] password;
@Value("${mongo.connections-per-host}")
private int connectionsPerHost;
@Value("${mongo.threads-allowed-to-block-for-connection-multiplier}")
private int threadsAllowedToBlockForConnectionMultiplier;
@Value("${mongo.connect-timeout}")
private int connectTimeout;
@Value("${mongo.max-wait-time}")
private int maxWaitTime;
@Value("${mongo.socket-keep-alive}")
private boolean socketKeepAlive;
@Value("${mongo.socket-timeout}")
private int socketTimeout;
//<mongo:mongo-client
// id="dapMongo"
// host="#{mongo_properties['mongo.host']}"
// port="#{mongo_properties['mongo.port']}"
// credentials="#{mongo_properties['mongo.username']}:#{mongo_properties['mongo.password']}@#{mongo_properties['mongo.database']}">
//
// <mongo:client-options
// connections-per-host="#{mongo_properties['mongo.connections-per-host']}"
// threads-allowed-to-block-for-connection-multiplier="#{mongo_properties['mongo.threads-allowed-to-block-for-connection-multiplier']}"
// connect-timeout="#{mongo_properties['mongo.connect-timeout']}"
// max-wait-time="#{mongo_properties['mongo.max-wait-time']}"
// socket-keep-alive="#{mongo_properties['mongo.socket-keep-alive']}"
// socket-timeout="#{mongo_properties['mongo.socket-timeout']}"/>
//
// </mongo:mongo-client>
@Bean(name = "mongoClient")
public MongoClient mongoClient(){
ServerAddress serverAddress = new ServerAddress(host, port);
List<MongoCredential> credentials = new LinkedList<MongoCredential>();
MongoCredential credential = MongoCredential.createCredential(username, db, password);
credentials.add(credential);
MongoClient mongoClient = new MongoClient(serverAddress, credentials, mongoOperations());
return mongoClient;
}
private MongoClientOptions mongoOperations(){
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.connectionsPerHost(connectionsPerHost);
builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
builder.connectTimeout(connectTimeout);
builder.maxWaitTime(maxWaitTime);
builder.socketKeepAlive(socketKeepAlive);
builder.socketTimeout(socketTimeout);
MongoClientOptions mongoOperations = builder.build();
return mongoOperations;
}
// <mongo:db-factory id="dapFactory" mongo-ref="dapMongo"
// dbname="#{mongo_properties['mongo.database']}"/>
@Bean(name = "mongoDbFactory")
public MongoDbFactory mongoDbFactory(@Qualifier("mongoClient")MongoClient mongoClient,
@Value("${mongo.database}")String database){
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, database);
return mongoDbFactory;
}
// <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
// <constructor-arg name="mongoDbFactory" ref="dapFactory"/>
// </bean>
@Bean(name = "db-mongoTemplate")
public MongoTemplate mongoTemplate(@Qualifier("mongoDbFactory")MongoDbFactory mongoDbFactory){
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
return mongoTemplate;
}
}
=========================================
CityServiceImpl.java
=========================================
@Service
public class CityServiceImpl implements CityService {
@Resource(name = "db-mongoTemplate")
private MongoTemplate mongoTemplate;
@Override
public void save(City city) {
mongoTemplate.save(city);
}
@Override
public City findByName(String cityName) {
Query query = new Query(Criteria.where("cityName").is(cityName));
City city = mongoTemplate.findOne(query, City.class);
return city;
}
@Override
public void updateCity(City city) {
Query query = new Query(Criteria.where("id").is(city.getId()));
Update update = new Update().set("cityName", city.getCityName()).set("description", city.getDescription());
//更新查询返回结果集的第一条
mongoTemplate.updateFirst(query, update, City.class);
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,UserEntity.class);
}
@Override
public void deleteById(Long id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, City.class);
}
}
=========================================
TestMongodb.java
=========================================
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class TestMongodb {
@Autowired
CityService cityService;
@Test
public void testSave(){
City city = new City();
city.setId(1l);
city.setCityName("test");
city.setDescription("hello");
city.setProvinceId(1l);
cityService.save(city);
}
}
=========================================
<!-- Spring Boot mongodb 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
=========================================
application.properties
=========================================
mongo.host=host
mongo.port=port
mongo.username=username
mongo.password=password
mongo.database=db
mongo.connections-per-host=10
mongo.threads-allowed-to-block-for-connection-multiplier=5
mongo.connect-timeout=60000
mongo.max-wait-time=120000
mongo.auto-connect-retry=true
mongo.socket-keep-alive=false
mongo.socket-timeout=0
=========================================
MongodbConfig.java
=========================================
@Configuration
public class MongodbConfig {
@Value("${mongo.host}")
private String host;
@Value("${mongo.port}")
private int port;
@Value("${mongo.username}")
private String username;
@Value("${mongo.database}")
private String db;
@Value("${mongo.password}")
private char[] password;
@Value("${mongo.connections-per-host}")
private int connectionsPerHost;
@Value("${mongo.threads-allowed-to-block-for-connection-multiplier}")
private int threadsAllowedToBlockForConnectionMultiplier;
@Value("${mongo.connect-timeout}")
private int connectTimeout;
@Value("${mongo.max-wait-time}")
private int maxWaitTime;
@Value("${mongo.socket-keep-alive}")
private boolean socketKeepAlive;
@Value("${mongo.socket-timeout}")
private int socketTimeout;
//<mongo:mongo-client
// id="dapMongo"
// host="#{mongo_properties['mongo.host']}"
// port="#{mongo_properties['mongo.port']}"
// credentials="#{mongo_properties['mongo.username']}:#{mongo_properties['mongo.password']}@#{mongo_properties['mongo.database']}">
//
// <mongo:client-options
// connections-per-host="#{mongo_properties['mongo.connections-per-host']}"
// threads-allowed-to-block-for-connection-multiplier="#{mongo_properties['mongo.threads-allowed-to-block-for-connection-multiplier']}"
// connect-timeout="#{mongo_properties['mongo.connect-timeout']}"
// max-wait-time="#{mongo_properties['mongo.max-wait-time']}"
// socket-keep-alive="#{mongo_properties['mongo.socket-keep-alive']}"
// socket-timeout="#{mongo_properties['mongo.socket-timeout']}"/>
//
// </mongo:mongo-client>
@Bean(name = "mongoClient")
public MongoClient mongoClient(){
ServerAddress serverAddress = new ServerAddress(host, port);
List<MongoCredential> credentials = new LinkedList<MongoCredential>();
MongoCredential credential = MongoCredential.createCredential(username, db, password);
credentials.add(credential);
MongoClient mongoClient = new MongoClient(serverAddress, credentials, mongoOperations());
return mongoClient;
}
private MongoClientOptions mongoOperations(){
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.connectionsPerHost(connectionsPerHost);
builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
builder.connectTimeout(connectTimeout);
builder.maxWaitTime(maxWaitTime);
builder.socketKeepAlive(socketKeepAlive);
builder.socketTimeout(socketTimeout);
MongoClientOptions mongoOperations = builder.build();
return mongoOperations;
}
// <mongo:db-factory id="dapFactory" mongo-ref="dapMongo"
// dbname="#{mongo_properties['mongo.database']}"/>
@Bean(name = "mongoDbFactory")
public MongoDbFactory mongoDbFactory(@Qualifier("mongoClient")MongoClient mongoClient,
@Value("${mongo.database}")String database){
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, database);
return mongoDbFactory;
}
// <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
// <constructor-arg name="mongoDbFactory" ref="dapFactory"/>
// </bean>
@Bean(name = "db-mongoTemplate")
public MongoTemplate mongoTemplate(@Qualifier("mongoDbFactory")MongoDbFactory mongoDbFactory){
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
return mongoTemplate;
}
}
=========================================
CityServiceImpl.java
=========================================
@Service
public class CityServiceImpl implements CityService {
@Resource(name = "db-mongoTemplate")
private MongoTemplate mongoTemplate;
@Override
public void save(City city) {
mongoTemplate.save(city);
}
@Override
public City findByName(String cityName) {
Query query = new Query(Criteria.where("cityName").is(cityName));
City city = mongoTemplate.findOne(query, City.class);
return city;
}
@Override
public void updateCity(City city) {
Query query = new Query(Criteria.where("id").is(city.getId()));
Update update = new Update().set("cityName", city.getCityName()).set("description", city.getDescription());
//更新查询返回结果集的第一条
mongoTemplate.updateFirst(query, update, City.class);
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,UserEntity.class);
}
@Override
public void deleteById(Long id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, City.class);
}
}
=========================================
TestMongodb.java
=========================================
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class TestMongodb {
@Autowired
CityService cityService;
@Test
public void testSave(){
City city = new City();
city.setId(1l);
city.setCityName("test");
city.setDescription("hello");
city.setProvinceId(1l);
cityService.save(city);
}
}
上一篇: springboot:quartz集群
下一篇: 纯java获取CPU序列号,生成机器码