mongodb-手写mongoclient加入到springmvc中

由于一个项目使用的是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) * 1000);  
        build.maxWaitTime(Integer.valueOf(maxWaitTime) * 1000);  
        MongoClientOptions options = build.build();  
        
        try {
            List addrs = new ArrayList();  
            for (String hostport : hostports.split(", *")) {
                if (StringUtils.isBlank(hostport)) {
                    continue;
                }
                hostport = hostport.trim();
                
                ServerAddress serverAddress = new ServerAddress(hostport.split(":")[0],Integer.valueOf(hostport.split(":")[1]));
                addrs.add(serverAddress);  
            }
              
            MongoCredential credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());  
            List credentials = new ArrayList();  
            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 mongoCollection(MongoDatabase mongoDatabase) {
        MongoCollection 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 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 "01".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中)