最近花了一些時間學習了下MongoDB數據庫,感受仍是比較全面系統的,涉及了軟件安裝、客戶端操做、安全認證、副本集和分佈式集羣搭建,以及使用Spring Data鏈接MongoDB進行數據操做,收穫很大。特此記錄,以備查看。html
文章目錄:git
MongoDB和Java(1):Linux下的MongoDB安裝github
MongoDB和Java(2):普通用戶啓動mongod進程spring
MongoDB和Java(3):Java操做MongoBmongodb
MongoDB和Java(4):Spring Data整合MongoDB(XML配置)數據庫
MongoDB和Java(5):Spring Data整合MongoDB(註解配置)安全
MongoDB和Java(6):Spring Data整合MongoDB副本集、分片集羣服務器
MongoDB和Java(7):MongoDB用戶管理socket
本文記錄如何使用註解配置方式整合Spring data和MongoDB,基礎的環境和使用xml整合是同樣的,不一樣的是:分佈式
1)刪除spring的xml配置文件
2)再也不編寫數據層的實現,而是使用Spring Data Mongodb掃描建立代理實現
源代碼下載
MongoDB和Java學習代碼.zip
這個類用於讀取mongo.properties中屬性
1 @Component 2 @PropertySource(value = "classpath:mongodb.properties") 3 public class MongoProperties { 4 5 @Value("${mongo.host}") 6 private String host; 7 8 @Value("${mongo.port}") 9 private Integer port; 10 11 @Value("${mongo.dbname}") 12 private String dbname; 13 14 @Value("${mongo.username}") 15 private String username; 16 17 @Value("${mongo.password}") 18 private String password; 19 20 @Value("${mongo.connectionsPerHost}") 21 private int connectionsPerHost; 22 23 @Value("${mongo.minConnectionsPerHost}") 24 private int minConnectionsPerHost; 25 26 @Value("${mongo.threadsAllowedToBlockForConnectionMultiplier}") 27 private int threadsAllowedToBlockForConnectionMultiplier; 28 29 @Value("${mongo.connectTimeout}") 30 private int connectTimeout; 31 32 @Value("${mongo.maxWaitTime}") 33 private int maxWaitTime; 34 35 @Value("${mongo.socketKeepAlive}") 36 private boolean socketKeepAlive; 37 38 @Value("${mongo.socketTimeout}") 39 private int socketTimeout; 40 41 // getter & setter 42 }
mongo.properties文件
1 mongo.host=10.10.13.195 2 mongo.port=27017 3 4 # 數據庫和驗證信息 5 mongo.dbname=test 6 mongo.username=xugf 7 mongo.password=123456 8 9 mongo.connectionsPerHost=8 10 mongo.minConnectionsPerHost=3 11 mongo.threadsAllowedToBlockForConnectionMultiplier=4 12 mongo.connectTimeout=1000 13 mongo.maxWaitTime=1500 14 mongo.socketKeepAlive=true 15 mongo.socketTimeout=1500
這個類用於配置MongoClient和DbFactory
咱們參考下官方文檔,https://github.com/spring-projects/spring-data-mongodb
1)配置類繼承AbstractMongoConfiguration
2)使用@EnableMongoRepositories註解開啓MongoRepsitory的掃描功能
看下這個類的代碼
1 @EnableMongoRepositories(basePackages = "org.net5ijy.mongo.dao") 2 @Configuration 3 @ComponentScan(basePackages = { "org.net5ijy.mongo" }) 4 public class MongoConfiguration extends AbstractMongoConfiguration { 5 6 @Autowired 7 private MongoProperties mongoProperties; 8 9 public MongoClient mongoClient() throws Exception { 10 11 // 獲取單機服務器環境 12 ServerAddress address = new ServerAddress(mongoProperties.getHost(), 13 mongoProperties.getPort()); 14 15 List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); 16 credentialsList.add(MongoCredential.createScramSha1Credential( 17 mongoProperties.getUsername(), mongoProperties.getDbname(), 18 mongoProperties.getPassword().toCharArray())); 19 20 Builder builder = MongoClientOptions.builder(); 21 22 builder.connectionsPerHost(mongoProperties.getConnectionsPerHost()); 23 builder.threadsAllowedToBlockForConnectionMultiplier(mongoProperties 24 .getThreadsAllowedToBlockForConnectionMultiplier()); 25 builder.connectTimeout(mongoProperties.getConnectTimeout()); 26 builder.maxWaitTime(mongoProperties.getMaxWaitTime()); 27 builder.socketKeepAlive(mongoProperties.isSocketKeepAlive()); 28 builder.socketTimeout(mongoProperties.getSocketTimeout()); 29 builder.minConnectionsPerHost(mongoProperties 30 .getMinConnectionsPerHost()); 31 32 return new MongoClient(address, credentialsList, builder.build()); 33 } 34 35 @Bean 36 public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 37 return new PropertySourcesPlaceholderConfigurer(); 38 } 39 40 @Override 41 protected String getDatabaseName() { 42 return mongoProperties.getDbname(); 43 } 44 45 @Override 46 public Mongo mongo() throws Exception { 47 return mongoClient(); 48 } 49 }
繼承MongoRepository
1 public interface EmployeeDao extends MongoRepository<Employee, String> { 2 3 void deleteByName(String name); 4 5 Employee findByName(String name); 6 }
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(classes = { MongoConfiguration.class }) 3 public class EmployeeDaoTest { 4 5 @Autowired 6 private EmployeeDao employeeDao; 7 8 @Autowired 9 private ConfigurableApplicationContext context; 10 11 @Test 12 public void testFindAll() throws Exception { 13 14 System.out.println("\n##### ApplicationContext class #####\n"); 15 16 System.out.println(context.getClass()); 17 18 System.out.println("\n##### Object names #####\n"); 19 20 String[] names = context.getBeanDefinitionNames(); 21 for (String name : names) { 22 System.out.println(name); 23 } 24 25 System.out.println("\n##### MongoDB employees #####\n"); 26 27 List<Employee> list = employeeDao.findAll(); 28 for (Employee employee : list) { 29 System.out.println(employee); 30 } 31 32 // Thread.sleep(10000); 33 34 context.close(); 35 } 36 37 @Test 38 public void testSave() { 39 Employee e = new Employee("admin", 28); 40 e.setSalary(4234.56); 41 employeeDao.save(e); 42 } 43 44 @Test 45 public void testDeleteByName() { 46 employeeDao.deleteByName("admin"); 47 } 48 49 @Test 50 public void testDelete() { 51 Employee e = employeeDao.findByName("admin"); 52 employeeDao.delete(e.getId()); 53 } 54 55 @Test 56 public void testFindByName() { 57 Employee e = employeeDao.findByName("admin"); 58 System.out.println(e); 59 } 60 61 @Test 62 public void testFindOne() { 63 Employee e = employeeDao.findByName("admin"); 64 Employee e2 = employeeDao.findOne(e.getId()); 65 System.out.println(e2); 66 } 67 }
和xml配置時編寫的測試類區別不大,就是
@ContextConfiguration(classes = { MongoConfiguration.class })
這裏有了變化
1 use admin 2 db.createUser({user: "admin", pwd: "123456", roles:[{role: "root", db: "admin" }]}) 3 4 use test 5 db.createUser({user: "xugf", pwd:"123456", roles:[{role:"dbOwner", db:"test"}]})
Spring Data MongoDB
https://github.com/spring-projects/spring-data-mongodb