1、首先创建MongoDB函数
众所周知,MongoDB中使用的使扩展的JS命令,所以定义函数,实际上也是定义一个JS函数,此处可以定义一个脚本,然后动态加载,这里我直接在数据库里面定义了一个函数,语句如下:
function convertDataTypes(start,end) {
function beginConvert(x) {
x.data = eval("(" + x.data + ")");
x.msgId = NumberInt(x.msgId);
x.ts = NumberLong(x.ts);
if (x.msgId == 1) {//GPS
x.data.lat = parseFloat(x.data.lat);
x.data.lon = parseFloat(x.data.lon);
x.data.dir = NumberInt(x.data.dir);
}
else {
print("false:msgId %s is not correct!",x.msgId);
return "false:msgId is not correct!";
}
db.module_statistic.save(x);
return "success";
}
var startString = new Date(start).toISOString();
var endString = new Date(end).toISOString();
var startTime = ISODate(startString);
var endTime = ISODate(endString);
db.module.find({"cdate":{$gte:startTime,$lte:endTime}}).forEach(function(x){beginConvert(x)});
var count = db.module_statistic.find({"cdate":{$gte:startTime,$lte:endTime}}).count();
return count;
}
这里是我在项目中的一个需求,定义的函数,主要是转换MongoDB里面的字符串数据到正确的数据类型,一边与后续的分析和统计。
二、权限设置
函数定义好了,接下来还有一个工作,因为需要在Spring中使用定时任务调用数据库的函数,这里需要使用到一个管道操作符$eval,关于这个操作符的详情,可以查看官方文档的介绍:eval ,有一处很重要:
If authorization is enabled, you must have access to all actions on all resources in order to run eval. Providing such access is not recommended, but if your organization requires a user to run eval, create a role that grants anyAction on anyResource. Do not assign this role to any other user.
这里大概是说,如果要执行这个操作,需要设置
anyAction
on anyResource 这样的一个角色的权限。于是创建角色,并赋给相应的用户:
db.createRole({role:'dbResource',roles:[],
privileges:[
{resource:{anyResource:true},actions:['anyAction']}
]})
db.updateUser("myuser", {
"roles" : [{
"role" : "readWrite",
"db" : "carcloud"
}, {
"role":"dbResource",
"db":"admin"}]
})
三、Java代码编写
数据库的准备好了,接下来就是Java里面的调用代码了。
CommandResult result =
neoModuleMsgDao.getCollection().getDB().doEval("convertDataTypes(" + startTime.getTime() + "," + endTime.getTime() + ")", "");
int count = result.getInt("retval", 0);
这里面,只是使用了MongoDB的Java驱动,具体可以自己去官网查看起使用方法,重要的就是doEval这个方法了
四、Spring定时任务
定时任务部分,最简单的就是Spring的注解了,网上攻略也很多,自己百度一下就知道怎么用,
1、配置Spring的xml文件
在xsi:schemaLocation中增加如下配置
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
再加入如下内容:
<!-- 自动扫描(自动注入),扫描me.gacl.service这个包以及它的子包的所有使用@Service注解标注的类 -->
<context:component-scan base-package="com.neo.auto.service" />
<!-- 配置定时任务的线程池,并使Spring可以识别@schedule注解-->
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
2、任务方法的配置
只需要在方法上加入如下注解即可:
@Scheduled(cron = "0 30 0 ? * *")