Arch-03-28 Jndi 配置 Mongodb jetty 实现

阅读更多

使用 springdata mongodb,直接使用 spring 配置,很简单,但如果一定要使用 jndi 方式配置,则需要费一翻功夫了。

 


		
	
	
 

 

1. jetty-evn.xml

 

 


  bean/plusMongoFactory
  
    
		192.168.1.24:30001,192.168.1.25:30001,192.168.1.27:30001		
		plussns
		
		
    
  

 

2. web.xml

 

 

	
		bean/plusMongoFactory
		com.plusrun.datasource.SpringMongoDbFactory
		Container
	

 

3. applicationContext.xml

 

 



 	
		
		
	
	
	
	
	
...

 

4. SpringMongoDbFactory.java

 

 

package com.plusrun.datasource;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;
import com.mongodb.ServerAddress;

public class SpringMongoDbFactory {

	private String serverName;
	private String databaseName;
	private String user;
	private String password;
	private static int DEFAULT_PORT = 27017;

	public MongoDbFactory mongoDbFactory() throws Exception {
		List addrs = new ArrayList();
		for (String addressStr : serverName.split(",")) {
			String server = addressStr;
			int port = DEFAULT_PORT;
			if (addressStr.indexOf(":") > 0) {
				server = addressStr.split(":")[0];
				port = Integer.parseInt(addressStr.split(":")[1]);
			}
			addrs.add(new ServerAddress(server, port));

		}

		UserCredentials userCredentials = new UserCredentials(user, password);
		return new SimpleMongoDbFactory(new Mongo(addrs), databaseName, userCredentials);
	}

	public MongoTemplate mongoTemplate() throws Exception {
		return new MongoTemplate(mongoDbFactory());
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

 

5. BaseSpringDataDao.java

 

 

...

	/**
	 * 设置 mongodb factory.
	 * @param mongoDbFactory -
	 */
	public void setDbFactory(final MongoDbFactory mongoDbFactory) {
		this.mongoDbFactory = mongoDbFactory;

	}


...

你可能感兴趣的:(Arch-03-28 Jndi 配置 Mongodb jetty 实现)