mongoDB数据库和Spring MVC的整合
之前一直用到的项目是Spring MVC+maven+mysql的,最近有些数据需要用到mongoDB数据库,现在做一些总结。
第一步:加载jar、maven配置
<!-- mongodb开始 -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
<!-- mongodb结束 -->
第二步:配置
1、集群配置
applicationContext.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:jee="http://www.springframework.org/schema/jee"
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-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/schema/util
http://www.springframework.org/schema/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd
"> <mongo:mongo id="mongo" replica-set="${mongodb.replicaSet}" />
<mongo:db-factory dbname="${mongodb.database}" mongo-ref="mongo"/> <!-- mongo模板操作对象 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean> </beans>
配置文件common-config.properties
mongodb.database=cxstatistics
mongodb.replicaSet = 10.0.11.28:27017,10.0.11.29:27017,10.0.11.30:27017
2、单机配置
applicationContext.xml
<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>
配置文件common-config.properties
mongo.dbname = test_db #数据库名称
mongo.password = test_pwd #密码
mongo.username = test_user #用户名
mongo.host = 127.0.0.1 #主机
mongo.port= 27017 #端口号
mongo.connectionsPerHost= 8 #一个线程变为可用的最大阻塞数
mongo.threadsAllowedToBlockForConnectionMultiplier= 4 #线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值
mongo.connectTimeout= 1500 #连接超时时间(毫秒)
mongo.maxWaitTime= 1500 #最大等待时间
mongo.autoConnectRetry= true #自动重连
mongo.socketKeepAlive= true #scoket保持活动
mongo.socketTimeout=1500 #scoket超时时间
mongo.slaveOk=true #读写分离
第三步、MongoDB的增删改查
1、Mongodb对象模型
Interview.java
@Document(collection="pagelog")
public class Interview implements Serializable { /**
*
*/
private static final long serialVersionUID = 1L; @Id
private String id; private String time;
private String desc;
private long _createtime;
private Integer _processed;
private long fid;
private String templateType;
private long puid; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public long get_createtime() {
return _createtime;
}
public void set_createtime(long _createtime) {
this._createtime = _createtime;
}
public Integer get_processed() {
return _processed;
}
public void set_processed(Integer _processed) {
this._processed = _processed;
}
public long getFid() {
return fid;
}
public void setFid(long fid) {
this.fid = fid;
}
public String getTemplateType() {
return templateType;
}
public void setTemplateType(String templateType) {
this.templateType = templateType;
}
public long getPuid() {
return puid;
}
public void setPuid(long puid) {
this.puid = puid;
} }
Pagecount.java
@Document(collection="countlog")
public class Pagecount implements Serializable{ /**
*
*/
private static final long serialVersionUID = 1L; @Id
private String id; private String time;
//private long fid;
List<Integer> fid = new ArrayList<Integer>();
//private Integer pagenum;
List<Integer> pagenum = new ArrayList<Integer>(); public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public List<Integer> getFid() {
return fid;
}
public void setFid(List<Integer> fid) {
this.fid = fid;
}
public List<Integer> getPagenum() {
return pagenum;
}
public void setPagenum(List<Integer> pagenum) {
this.pagenum = pagenum;
} }
2、查询示例代码
接口:
/**
* 得到时间区间内的统计数据
* @param beginDate
* @param endDate
* @return
*/
public long getInterviewNum(String beginDate, String endDate);
/**
* 得到时间区间内根据fid排序的统计数据list
* @param beginDate
* @return
*/
public List<Pagecount> getPageGroup(String beginDate);
接口实现:
@Override
@Path("getInterviewNum")
@GET
@Produces({"application/json; charset=UTF-8"})
public long getInterviewNum(@QueryParam("beginDate")String beginDate, @QueryParam("endDate")String endDate) {
long Num=mongo.count(new Query(Criteria.where("time").gt(beginDate).lte(endDate)), Interview.class);
return Num;
}
@Override
@Path("getPageGroup")
@GET
@Produces({"application/json; charset=UTF-8"})
public List<Pagecount> getPageGroup(@QueryParam("beginDate")String beginDate) {
Criteria criatira= new Criteria();
criatira.andOperator(Criteria.where("time").is(beginDate));
List<Pagecount> pagecount = new ArrayList<Pagecount>();
String year= beginDate.substring(0,4);
String month=beginDate.substring(5);
mongo.getDb().eval("pagelog("+year+","+month+")");
//mongo.getDb().eval("pagelog("+beginDate+")", pagecount);
pagecount= mongo.find(new Query(criatira).with(new Sort(new Order(Direction.DESC, "pagenum"))), Pagecount.class);
return pagecount;
}
控制层:
@Path("")
public class InterviewController { @Autowired
StatisticsService statisticsService; @Post("/interview")
@Get("/interview")
@AdminLoginRequired
public String index(Invocation inv) {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String mDateTime=formatter.format(c.getTime());
inv.addModel("dateTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
inv.addModel("mDateTime", mDateTime);
return "/views/statistics/interview.vm";
} @Post("/getInterview")
@Get("/getInterview")
public String getInterview(Invocation inv,@Param("beginDate")String beginDate,@Param("endDate")String endDate){
long Num = statisticsService.getInterviewNum(beginDate, endDate);
inv.addModel("Num", Num);
JSONObject json = new JSONObject();
json.put("Num", Num);
return "@"+json;
} @Post("/interviewGroup")
@Get("/interviewGroup")
@AdminLoginRequired
public String indexGroup(Invocation inv) {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
String mDateTime=formatter.format(c.getTime());
inv.addModel("mDateTime", mDateTime);
return "/views/statistics/interviewGroup.vm";
} @Post("/getPageGroup")
@Get("/getPageGroup")
public String getPageGroup(Invocation inv,@Param("beginDate")String beginDate){
List<Pagecount> Pagecount = new ArrayList<Pagecount>();
Pagecount = statisticsService.getPageGroup(beginDate);
JSONObject json = new JSONObject();
json.put("list", Pagecount);
return "@"+json;
}
}
3、mongoDB存储过程:
function(year,month){
var time=year+'-'+month;
if(month<10){
time=year+'-0'+month;
}
var num=[];
var fid=[];
db.getCollection('pagelog').aggregate([ { $match : {'time':{$regex: "^" + time + ".*$"}} },{$group : { _id : "$fid", num : {$sum : 1}}}]).forEach(function(obj){
num.push(obj.num);
fid.push(obj._id);
})
document1=num;
document2=fid;
db.countlog.update({'time':time},{$set:{'fid':document2,'pagenum':document1,'time':time}},true,true);
return time;
}
mongoDB数据库和Spring MVC的整合的更多相关文章
- Spring Data MongoDB example with Spring MVC 3.2
Spring Data MongoDB example with Spring MVC 3.2 Here is another example web application built with S ...
- Thymeleaf 3与Spring MVC 4 整合配置
Thymeleaf 3与Spring MVC 4 整合配置 Maven 依赖配置 Spring 相关依赖就不说了 <dependency> <groupId>org.thyme ...
- 玩转spring mvc(四)---在spring MVC中整合JPA
关于在Spring MVC中整合JPA是在我的上一篇关于spring mvc基本配置基础上进行的,所以大家先参考一下我的上一篇文章:http://blog.csdn.net/u012116457/ar ...
- ssm整合说明与模板-Spring Spring MVC Mybatis整合开发
ssm整合说明 spring+spring mvc+mybatis 说明 源码下载 由于之前存在ssh框架,spring+struts+hibernate,其中spring负责aop与ioc,所以一般 ...
- Spring+MVC+Mybatis整合
本文是对慕课网上"搞定SSM开发"路径的系列课程的总结,详细的项目文档和课程总结放在github上了.点击查看 什么是秒杀业务 网站售卖某产品时,规定在某个日期开始售卖限量的产品, ...
- Spring+Spring MVC+MyBatis整合
一.准备工作 1.1导入所需jar包 1.2数据库 CREATE TABLE `t_customer` ( `id` ) NOT NULL AUTO_INCREMENT, `username` ...
- spring, spring mvc, mybatis整合文件配置详解
转自:http://www.cnblogs.com/wxisme/p/4924561.html 使用SSM框架做了几个小项目了,感觉还不错是时候总结一下了.先总结一下SSM整合的文件配置.其实具体的用 ...
- Spring + Spring MVC + MyBatis 整合
1.所需要Jar包 ? <!-- Spring3.0.1包 --> org.springframework.web-3.0.1 系列 <!-- 公共包 --> sl ...
- Spring4+Spring MVC+MyBatis整合思路
1.Spring框架的搭建 这个很简单,只需要web容器中注册org.springframework.web.context.ContextLoaderListener,并指定spring加载配置文件 ...
随机推荐
- Kindle DXG和Win10 64bits无法连接的问题
直入主题:换根数据线. 不要觉得答案简单,我就是不负责任的在调侃. 在得出这条答案之前,我的思路是,既然插上线以后,kindle的充电指示灯会亮,那就应该不是线的问题. 所以实际的过程是我安装了驱动之 ...
- /px/em/rem/的区别
PX特点: 1 .IE无法调整那些使用px作为单位的字体大小: 2. 国外的大部分网站能够调整的原因在于其使用了em或rem作为字体单位: 3.Firefox能够调整px和em,rem,但是96%以上 ...
- Java中的构造代码块
代码块 ----a静态代码块 ----b构造代码块 ----c普通代码块 执行顺序:(优先级从高到低.)静态代码块>mian方法>构造代码块>构造方法. a.静态代码块: 静态代码块 ...
- javascript中call函数与apply
javascript中的call方法使当前对象可以调用另一个对象的方法,即改变this的指向内容 var first_object = { num: 42 }; var second_object = ...
- 想让你的java代码更漂亮,用枚举吧
枚举是java 5之后添加的一个重要特性,这个特性不能提高性能,但是能让java程序员写出更优雅的代码. 我之前看到过挺多介绍java枚举的不错的帖子,我也来参与以下这个话题. 1. 枚举基本用法 / ...
- [转]./configure,make,make install的作用
./configure,make,make install的作用(转) 这些都是典型的使用GNU的AUTOCONF和AUTOMAKE产生的程序的安装步骤. ./configure是用来检测你的安装平台 ...
- mybatis实战教程(mybatis in action)之一:开发环境搭建
mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载. 首先建立一 ...
- Pychram如何导入Django项目
最近在学Django,用GitHub来保存项目.但当从GitHub中clone出来后,Pycharm怎么来运行项目呢? 首先要对项目进行设置,使其能支持Django,具体设置如下: 在Pycharm中 ...
- 【学】ECMA6的新特性1
ECMA6的新特性1 let特性: 1.不允许重复声明 2.没有预解析 3.块级作用域 一对{}包括的区域称为代码块 块级作用域指一个变量或者函数只在该区域才起作用. 例1: console.log( ...
- BFS与DFS
DFS:使用栈保存未被检测的结点,结点按照深度优先的次序被访问并依次被压入栈中,并以相反的次序出栈进行新的检测. 类似于树的先根遍历深搜例子:走迷宫,你没有办法用分身术来站在每个走过的位置.不撞南山不 ...