这里的ssm不是指的spring+springmvc+mybatis,而是指的spring+springmvc+mongodb,下面我将搭建一个简单的“ssm”框架。
1、新建一个maven项目,骨架使用webapp骨架。
2、在pom.xml中加入依赖。
1 <dependencies> 2 <!-- 1. spring依赖 --> 3 <dependency> 4 <groupId>org.springframework</groupId> 5 <artifactId>spring-context</artifactId> 6 <version>4.3.7.RELEASE</version> 7 </dependency> 8 <dependency> 9 <groupId>org.springframework</groupId> 10 <artifactId>spring-web</artifactId> 11 <version>4.3.7.RELEASE</version> 12 </dependency> 13 <dependency> 14 <groupId>org.springframework</groupId> 15 <artifactId>spring-webmvc</artifactId> 16 <version>4.3.7.RELEASE</version> 17 </dependency> 18 <dependency> 19 <groupId>org.aspectj</groupId> 20 <artifactId>aspectjweaver</artifactId> 21 <version>1.8.10</version> 22 </dependency> 23 <dependency> 24 <groupId>org.springframework</groupId> 25 <artifactId>spring-jdbc</artifactId> 26 <version>4.3.7.RELEASE</version> 27 </dependency> 28 <dependency> 29 <groupId>org.springframework</groupId> 30 <artifactId>spring-context-support</artifactId> 31 <version>4.3.7.RELEASE</version> 32 </dependency> 33 34 <!-- 2. mongoDB依赖 --> 35 <dependency> 36 <groupId>org.springframework.data</groupId> 37 <artifactId>spring-data-mongodb</artifactId> 38 <version>1.7.0.RELEASE</version> 39 </dependency> 40 41 <!-- 3. 日志依赖 --> 42 <dependency> 43 <groupId>log4j</groupId> 44 <artifactId>log4j</artifactId> 45 <version>1.2.12</version> 46 </dependency> 47 48 <!-- 4. 其他依赖 --> 49 <dependency> 50 <groupId>javax.servlet.jsp</groupId> 51 <artifactId>jsp-api</artifactId> 52 <version>2.1</version> 53 </dependency> 54 <dependency> 55 <groupId>javax.servlet</groupId> 56 <artifactId>javax.servlet-api</artifactId> 57 <version>3.0.1</version> 58 </dependency> 59 <dependency> 60 <groupId>javax.servlet</groupId> 61 <artifactId>jstl</artifactId> 62 <version>1.2</version> 63 </dependency> 64 <dependency> 65 <groupId>org.codehaus.jackson</groupId> 66 <artifactId>jackson-mapper-asl</artifactId> 67 <version>1.9.13</version> 68 </dependency> 69 <dependency> 70 <groupId>com.fasterxml.jackson.core</groupId> 71 <artifactId>jackson-annotations</artifactId> 72 <version>2.6.1</version> 73 </dependency> 74 <dependency> 75 <groupId>com.fasterxml.jackson.core</groupId> 76 <artifactId>jackson-core</artifactId> 77 <version>2.6.1</version> 78 </dependency> 79 <dependency> 80 <groupId>com.fasterxml.jackson.core</groupId> 81 <artifactId>jackson-databind</artifactId> 82 <version>2.6.1</version> 83 </dependency> 84 </dependencies>
3、在web.xml中配置springmvc以及编码过滤器。
1 <!-- 编码过滤器 --> 2 <filter> 3 <filter-name>CharacterEncoding</filter-name> 4 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 5 <init-param> 6 <param-name>encoding</param-name> 7 <param-value>utf-8</param-value> 8 </init-param> 9 </filter> 10 <filter-mapping> 11 <filter-name>CharacterEncoding</filter-name> 12 <url-pattern>/*</url-pattern> 13 </filter-mapping> 14 15 <!-- springmvc配置 --> 16 <servlet> 17 <servlet-name>mvc</servlet-name> 18 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 19 <init-param> 20 <param-name>contextConfigLocation</param-name> 21 <param-value>classpath:spring-mvc.xml</param-value> 22 </init-param> 23 <load-on-startup>1</load-on-startup> 24 </servlet> 25 <servlet-mapping> 26 <servlet-name>mvc</servlet-name> 27 <url-pattern>/</url-pattern> 28 </servlet-mapping>
4、配置文件部分,首先加入日志配置文件:log4j.properties
1 log4j.rootLogger = DEBUG,file,stdout,error 2 3 log4j.appender.file = org.apache.log4j.RollingFileAppender 4 log4j.appender.file.File = D:/Logs/skyer/ssm-mongo.log 5 log4j.appender.file.MaxFileSize = 10MB 6 log4j.appender.file.MaxBackupIndex = 20 7 log4j.appender.file.Append = true 8 log4j.appender.file.layout = org.apache.log4j.PatternLayout 9 log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] [%t] (%F:%L)->%m %n 10 11 log4j.appender.stdout = org.apache.log4j.ConsoleAppender 12 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
5、加入mongodb配置文件:mongodb.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xmlns:context="http://www.springframework.org/schema/context" 8 xmlns:mongo="http://www.springframework.org/schema/data/mongo" 9 xsi:schemaLocation="http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 15 http://www.springframework.org/schema/util 16 http://www.springframework.org/schema/util/spring-util-3.0.xsd 17 http://www.springframework.org/schema/data/mongo 18 http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd 19 http://www.springframework.org/schema/context 20 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 21 22 <context:component-scan base-package="com.skyer" /> 23 <!-- 获取配置资源 --> 24 <context:property-placeholder location="classpath:mongodb.properties" /> 25 26 <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}"> 27 <mongo:options connections-per-host="${mongo.connectionsPerHost}" 28 threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" 29 connect-timeout="${mongo.connectTimeout}" 30 max-wait-time="${mongo.maxWaitTime}" 31 auto-connect-retry="${mongo.autoConnectRetry}" 32 socket-keep-alive="${mongo.socketKeepAlive}" 33 socket-timeout="${mongo.socketTimeout}" 34 slave-ok="${mongo.slaveOk}" 35 write-number="1" 36 write-timeout="0" 37 write-fsync="true" /> 38 </mongo:mongo> 39 40 <!-- 设置使用的数据库名 --> 41 <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongo" /> 42 43 <!-- mongodb的模板 --> 44 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> 45 <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> 46 </bean> 47 48 </beans>
6、加入mongodb的配置文件:mongodb.properties
1 #数据库名称 2 mongo.dbname = db_name 3 #数据库地址 4 mongo.host=192.168.112.128 5 #数据库端口 6 mongo.port=27017 7 #一个线程变为可用的最大阻塞数 8 mongo.connectionsPerHost=8 9 #线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值 10 mongo.threadsAllowedToBlockForConnectionMultiplier=4 11 #连接超时时间(毫秒) 12 mongo.connectTimeout=1000 13 #最大等待时间 14 mongo.maxWaitTime=1500 15 #自动重连 16 mongo.autoConnectRetry=true 17 #scoket保持活动 18 mongo.socketKeepAlive=true 19 mongo.socketTimeout=1500 20 #读写分离 21 mongo.slaveOk=true 22 mongo.writeNumber=1 23 mongo.riteTimeout=0 24 mongo.writeFsync=true
7、加入spring的配置文件:spring-mvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:mvc="http://www.springframework.org/schema/mvc" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx.xsd 15 http://www.springframework.org/schema/mvc 16 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 17 18 <!-- 引入mongoDB文件 --> 19 <import resource="classpath:mongodb.xml"/> 20 21 <!-- 配置视图解析器 --> 22 <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 23 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> 24 <!-- 前缀:在视图名前加上前缀 --> 25 <property name="prefix" value="/" /> 26 <!-- 后缀:在视图名后加上后缀 --> 27 <property name="suffix" value=".jsp" /> 28 </bean> 29 30 <!-- 扫描注解驱动 --> 31 <mvc:annotation-driven /> 32 <!-- 配置扫描器 --> 33 <context:component-scan base-package="com.skyer" /> 34 35 </beans>
8、建立项目的包和一些类,项目目录结构如下。
9、下面对项目中每一个类具体说明,先说User实体类:User.java
1 // collection指定的相当于MySQL中的表名,也可以不指定,默认为实体类类名 2 @Document(collection = "db_skyer_user") 3 public class User { 4 5 @Id 6 private int id; 7 private String name; 8 private String pwd; 9 private Date birthday; 10 11 // getter和setter方法省略,请自行补上。 12 13 }
10、统一返回值实体类:ResultInfo.java
1 public class ResultInfo<T> { 2 3 private int code; // 返回代码(200:成功,500:失败) 4 private T data; // 返回的数据,正确的信息或错误描述信息 5 6 // getter和setter方法省略,请自行补上。 7 8 }
11、Controller基类:BaseController.java
1 public abstract class BaseController { 2 3 /** 4 * 请求成功 5 * 6 * @param data 请求成功返回的内容 7 * @return 8 */ 9 public Object success(Object data) { 10 ResultInfo<Object> resultInfo = new ResultInfo<Object>(); 11 resultInfo.setCode(200); 12 resultInfo.setData(data); 13 return resultInfo; 14 } 15 16 /** 17 * 请求失败 18 * 19 * @param msg 失败信息 20 * @return 21 */ 22 public Object fail(String msg) { 23 ResultInfo<Object> resultInfo = new ResultInfo<Object>(); 24 resultInfo.setCode(500); 25 resultInfo.setData(msg); 26 return resultInfo; 27 } 28 29 }
12、测试控制器:DemoController.java(注:这里的添加的时候,使用了for循环添加了100W条数据,为后续的索引测试使用)
1 @Controller 2 @RequestMapping("/demo") 3 public class DemoController extends BaseController { 4 5 private static final Logger L = Logger.getLogger(DemoController.class); 6 7 @Autowired 8 private UserDao userDao; 9 10 /** 11 * 通过主键查询 12 * 13 * @param id 14 * @return 15 */ 16 @RequestMapping("/findById/{id}") 17 @ResponseBody 18 public Object findById(@PathVariable("id") int id) { 19 try { 20 return super.success(userDao.findById(id)); 21 } catch (Exception e) { 22 L.error("-------------------" + e); 23 e.printStackTrace(); 24 } 25 return super.fail("查询错误!"); 26 } 27 28 /** 29 * 添加 30 */ 31 @RequestMapping("/add") 32 @ResponseBody 33 public Object add() { 34 try { 35 userDao.add(); 36 return super.success("添加成功!"); 37 } catch (Exception e) { 38 L.error("-------------------" + e); 39 e.printStackTrace(); 40 } 41 return super.fail("添加失败!"); 42 } 43 44 }
13、UserDao层:UserDao.java
1 @Repository 2 public class UserDao { 3 4 @Resource 5 private MongoTemplate mongoTemplate; 6 7 public Object findById(int id) { 8 long begin = System.currentTimeMillis(); 9 List<User> list = mongoTemplate.find(new Query(Criteria.where("name").is("name5217")), User.class); 10 long end = System.currentTimeMillis(); 11 System.out.println("查询用时:" + (end - begin) + "毫秒。"); 12 return list; 13 } 14 15 public boolean add() { 16 User user = null; 17 long begin = System.currentTimeMillis(); 18 System.out.println("开始插入。。。"); 19 for (int i = 0; i < 1000000; i++) { 20 user = new User(); 21 user.setId(i); 22 user.setName("name" + i); 23 user.setPwd("pwd" + i); 24 user.setBirthday(new Date()); 25 mongoTemplate.insert(user); 26 if (i % 1000 == 0) { 27 System.out.println("第" + ((i / 1000) + 1) + "批插入成功,本批次共1000条数据。。。"); 28 } 29 } 30 long end = System.currentTimeMillis(); 31 System.out.println("插入完毕,共100W条数据,累计用时:" + (end - begin) / 1000 + "秒。"); 32 return true; 33 } 34 35 }
14、代码这就完毕了,剩下的就是测试,启动web项目,访问对应的接口即可。下面贴几张我测试时候的截图。
a. 添加100W条记录:
b. 不加索引查询:
c. 加索引之后查询: