由于一个项目使用的是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. SoC FPGA JTAG电路设计 要点

    JTAG协议制定了一种边界扫描的规范,边界扫描架构提供了有效的测试布局紧凑的PCB板上元件的能力.边界扫描可以在不使用物理测试探针的情况下测试引脚连接,并在器件正常工作的过程中捕获运行数据. SoC ...

  2. 用Java取指定时区的时间 北京时间,纽约时间,班加罗尔时间

    /** * 取北京时间 * @return */ public static String getBeijingTime(){ return getFormatedDateString(8); } / ...

  3. pl/sql 语言设置

    1.select * from v$nls_parameters 查询nls的参数,获得数据库服务器端的字符编码 NLS_LANGUAGE NLS_CHARACTERSET 2.修改本地环境变量 NL ...

  4. iOS Development和iOS Distribution有什么区别

    http://zhidao.baidu.com/link?url=T9od33JuA7jjxzfyV-wOjuVLSNUaqpc9aoCu2HjfYfHBuRLW1CNDii0Bh9uvG6h-GeJ ...

  5. html.EditorForModel自定义模版

    https://www.cnblogs.com/lori/p/5969658.html  http://www.cnblogs.com/yinzixin/archive/2012/12/18/2821 ...

  6. Eclipse ADT 代码注释模版

    具体怎么用: 将下面的内容拷贝出来保存为XML文件,进入,Eclipse :Window --> Java --> Code Style --> Code Templates-> ...

  7. INDEX--创建索引和删除索引时的SCH_M锁

    最近有一个困惑,生产服务器上有一表索引建得乱七八糟,经过整理后需要新建几个索引,再删除几个索引,建立索引时使用联机(ONLINE=ON)创建,查看下服务器负载(磁盘和CPU压力均比较低的情况)后就选择 ...

  8. 5.WebAPI的Filter

    1.WebApi的Filter介绍: 大家知道什么是AOP(aspect oriented programming)吗?它是可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添 ...

  9. 记录.NET Core部署到Linux之.NET Core环境搭建(1)

    1.在安装.NET之前,您需要注册Microsoft密钥.注册产品存储库和安装所需的依赖项. 启动我们的虚拟机,输入以下命令: sudo rpm -Uvh https://packages.micro ...

  10. 用ndp部署storm应用

    本文由作者余宝虹授权网易云社区发布. 使用户ndp部署一个Java应用大家都非常熟悉的,但是看到某些同学用非常繁琐的方式部署storm应用的时候,我觉得很有必要整一个帮助教程,ndp帮助文档里面没有, ...