由于一个项目使用的是springmvc3.x版本, mongodb使用的为3.x版本, 所以springmvc继承的mongodb-data并不可用, 只能自己手写一个mongoclient并加入到spring-context中去

参数使用springmvc通过配置文件向bean中注入的方式

package com.iwhere.rongyun.config;

import java.util.ArrayList;
import java.util.List; import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.iwhere.rongyun.utils.DateUtils;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; @Configuration
public class MongoConfig {
private static Logger LOGGER = LoggerFactory.getLogger(MongoConfig.class); @Value("${mongodb.hostports}")
private String hostports; @Value("${mongodb.maxConnect}")
private String maxConnect;
@Value("${mongodb.maxWaitThread}")
private String maxWaitThread;
@Value("${mongodb.maxTimeOut}")
private String maxTimeOut;
@Value("${mongodb.maxWaitTime}")
private String maxWaitTime; @Value("${mongodb.username}")
private String username;
@Value("${mongodb.password}")
private String password;
@Value("${mongodb.database}")
private String database;
@Value("${mongodb.collection}")
private String collection; @Bean
public MongoClient mongoClient() {
MongoClient mongoClient = null; MongoClientOptions.Builder build = new MongoClientOptions.Builder();
build.connectionsPerHost(Integer.valueOf(maxConnect));
build.threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(maxWaitThread));
build.connectTimeout(Integer.valueOf(maxTimeOut) * );
build.maxWaitTime(Integer.valueOf(maxWaitTime) * );
MongoClientOptions options = build.build(); try {
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
for (String hostport : hostports.split(", *")) {
if (StringUtils.isBlank(hostport)) {
continue;
}
hostport = hostport.trim(); ServerAddress serverAddress = new ServerAddress(hostport.split(":")[],Integer.valueOf(hostport.split(":")[]));
addrs.add(serverAddress);
} MongoCredential credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential); mongoClient = new MongoClient(addrs,credentials, options);
LOGGER.info("20-02 " + DateUtils.getDateTime() + " 10-03 " + "admin" + " mongodb客户端创建成功 " + "admin");
} catch (Exception e) {
LOGGER.info("20-02 " + DateUtils.getDateTime() + " 10-03 " + "admin" + " mongodb客户端创建失败 " + "admin");
e.printStackTrace();
}
return mongoClient;
} @Bean
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(database);
return mongoDatabase;
} @Bean
public MongoCollection<Document> mongoCollection(MongoDatabase mongoDatabase) {
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collection);
// mongoDatabase.createCollection(collection);
return mongoCollection;
} }

然后是service层

package com.iwhere.rongyun.mongodb.impl;

import static com.mongodb.client.model.Filters.eq;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON;
import com.iwhere.rongyun.mongodb.MongoService;
import com.iwhere.rongyun.utils.DateUtils;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.FindOneAndUpdateOptions; @Service
@Transactional
public class MongoServiceImpl implements MongoService {
private static Logger LOGGER = LoggerFactory.getLogger(MongoServiceImpl.class); @Autowired
private MongoCollection<Document> mongoCollection; @Override
public Boolean isUserLogin(String userId) {
Document first = mongoCollection.find(eq("userId", userId)).first();
if (first == null) {
LOGGER.info("20-02 " + DateUtils.getDateTime() + " 10-03 " + userId + " 用户不存在 " + userId);
return false;
}
String flag = first.getString("status");
LOGGER.info("20-02 " + DateUtils.getDateTime() + " 10-03 " + userId + " 用户存在 " + first);
return "".equals(flag) ? true : false;
} @Override
public Boolean upsert(String userId, String status, String os, String time) {
Document update = new Document();
update.append("status", status);
update.append("os", os);
update.append("time", time);
try {
@SuppressWarnings("unused")
Document result = mongoCollection.findOneAndUpdate(eq("userId", userId), new Document("$set", update),
new FindOneAndUpdateOptions().upsert(true)); update.append("userId", userId);
LOGGER.info("20-02 " + DateUtils.getDateTime() + " 10-03 " + userId + " mongodb存储成功 "
+ JSON.toJSONString(update));
return true;
} catch (Exception e) {
update.append("userId", userId);
LOGGER.info("20-02 " + DateUtils.getDateTime() + " 10-03 " + userId + " mongodb存储失败 "
+ JSON.toJSONString(update) + "-" + e.getMessage());
e.printStackTrace();
return false;
}
} }

mongodb-手写mongoclient加入到springmvc中的更多相关文章

  1. java手写线程池,完善中

    package com.test001.threadpool; import java.util.LinkedList; import java.util.List; import java.util ...

  2. 【手写代码】计算1-n中总共有多少二进制1

    #include<bits/stdc++.h> #include<vector> using namespace std; //时间复杂度:O(N) int f(int x) ...

  3. c++后台开发面试常见知识点总结(六)算法手写

    链表倒转  leetcode-206 连续子数组最大和问题(和最大的连续子序列的和)   leetcode-53 输出字符串中最长的回文子串长度?  leetcode-5 一个字符串,求最长无重复子串 ...

  4. 【深度学习系列】手写数字识别卷积神经--卷积神经网络CNN原理详解(一)

    上篇文章我们给出了用paddlepaddle来做手写数字识别的示例,并对网络结构进行到了调整,提高了识别的精度.有的同学表示不是很理解原理,为什么传统的机器学习算法,简单的神经网络(如多层感知机)都可 ...

  5. AI应用开发实战 - 手写算式计算器

    扩展手写数字识别应用 识别并计算简单手写数学表达式 主要知识点 了解MNIST数据集 了解如何扩展数据集 实现手写算式计算器 简介 本文将介绍一例支持识别手写数学表达式并对其进行计算的人工智能应用的开 ...

  6. 李宏毅 Keras手写数字集识别(优化篇)

    在之前的一章中我们讲到的keras手写数字集的识别中,所使用的loss function为‘mse’,即均方差.那我们如何才能知道所得出的结果是不是overfitting?我们通过运行结果中的trai ...

  7. MindSpore手写数字识别初体验,深度学习也没那么神秘嘛

    摘要:想了解深度学习却又无从下手,不如从手写数字识别模型训练开始吧! 深度学习作为机器学习分支之一,应用日益广泛.语音识别.自动机器翻译.即时视觉翻译.刷脸支付.人脸考勤--不知不觉,深度学习已经渗入 ...

  8. 手写Json解析器学习心得

    一. 介绍 一周前,老同学阿立给我转了一篇知乎回答,答主说检验一门语言是否掌握的标准是实现一个Json解析器,网易游戏过去的Python入门培训作业之一就是五天时间实现一个Json解析器. 知乎回答- ...

  9. 手写Spring AOP,快来瞧一瞧看一看撒!

    目录 AOP分析 Advice实现 定义Advice接口 定义前置.后置.环绕和异常增强接口 Pointcut实现 定义PointCut接口 定义正则表达式的实现类:RegExpressionPoin ...

随机推荐

  1. The MATLAB Profiler

    function a = myFunc(a,b,c,d,e) : a = a-b + c^d*log(e); end end >> profile on; myFunc(a,b,c,d,e ...

  2. Html隐藏占空间与隐藏不占空间

    隐藏不占用空间: display:none; 以下为示例代码: <span style="display:none;"> 获取中</span> 隐藏占用空间 ...

  3. linux系统编程之文件与IO(八):文件描述符相关操作-dup,dup2,fcntl

    本节目标: 1,文件共享 打开文件内核数据结构 一个进程两次打开同一个文件 两个进程打开同一个文件 2,复制文件描述符(dup.dup2.fcntl) 一,文件共享 1,一个进程打开两个文件内核数据结 ...

  4. 从 exe.config 读取appSettings 中的配置数据

    右键解决方案,添加引用--> System.Configuration.dll 在exe.config 中添加数据 <appSettings> <add key=" ...

  5. 2D Polygons( Poygon) CGAL 4.13 -User Manual

    1 Introduction A polygon is a closed chain of edges. Several algorithms are available for polygons. ...

  6. 【cocos2d-x + Lua(1) 绑定Lua并使用tolua++】

    为什么要使用Lua进行游戏开发?转载请注明出处http://www.cnblogs.com/zisou/p/cocos2dx-lua1.html 上面一个问题我觉得在我们使用Lua之前需要深入思考的, ...

  7. 日常一些出现bug的问题

    1.Fatal signal 4 (SIGILL), code 1, fault addr 0xca31569e in tid 8033 (r.myapplication) fault addr : ...

  8. jzoj5925

    tj:這道題題解有錯 水法ac代碼如下: #include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n ...

  9. 面对对象编程(OOP, Object Oriented Programming)及其三个基本特性

    一千个读者,一千个哈姆雷特.对于面对对象编程,书上都会告诉我们它有三个基本特性,封装,继承,多态,但谈起对这三点的见解,又是仁者见仁智者见智,感觉还是得多去编程中体验把 . 面向对象编程(OOP, O ...

  10. [nuget]VS中包管理器打开后找不到其它工程的问题

    今天新建工程做小组内用的工具,打算做个winform的项目, 用vs新建了winform项目,简单分下层吧,又加了两个类库项目, 然后,要用到的包需要nuget安装,于是发生这个问题: [VS]在so ...