spring boot使用mongodb

使用mongodb思路
  • 引入spring boot mongodb jar包
  • 配置mongodb相关信息
  • 测试使用
引入mongodb jar包

在spring boot demo工程pom.xml文件中新增

 
        org.springframework.boot
        spring-boot-starter-data-mongodb

mongodb相关配置
  • 在application.properties中配置,3.0以上版本支持如下配置
spring.data.mongodb.uri=mongodb://test:[email protected]:27016/test
  • 自定义配置
    如果我们想配置mongodb连接池,默认是没有提供配置方式,所以需要自定义完成配置
    (1) 新建mongo.properties,配置内容如下
mongodb.custom.host=127.0.0.1
mongodb.custom.port=27016
#mongodb.custom.replica-set=
mongodb.custom.username=test
mongodb.custom.password=test
mongodb.custom.database=report
mongodb.custom.authentication-database=test
mongodb.custom.connections-per-host=20
mongodb.custom.min-connections-per-host=20

(2) 重写MongoDbFactory,创建client和Factory,代码如下

package com.geneseeq.access.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

@Configuration
@PropertySource("classpath:config/mongo.properties")
public class MongoConfig {

    @Value("${mongodb.custom.host}")
    private String host;

    @Value("${mongodb.custom.port}")
    private Integer port;

//    @Value("${mongodb.custom.replica-set}")
//    private String replicaSet;

    @Value("${mongodb.custom.username}")
    private String username;

    @Value("${mongodb.custom.password}")
    private String password;

    @Value("${mongodb.custom.database}")
    private String database;

    @Value("${mongodb.custom.authentication-database}")
    private String authenticationDatabase;

    @Value("${mongodb.custom.connections-per-host}")
    private Integer connectionsPerHost = 10;

    @Value("${mongodb.custom.min-connections-per-host}")
    private Integer minConnectionsPerHost = 2;

    // 覆盖默认的MongoDbFactory
    @Bean
    MongoDbFactory mongoDbFactory() {
        //客户端配置(连接数、副本集群验证)
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(connectionsPerHost);
        builder.minConnectionsPerHost(minConnectionsPerHost);
//        if (replicaSet != null) {
//            builder.requiredReplicaSetName(replicaSet);
//        }
        MongoClientOptions mongoClientOptions = builder.build();

        // MongoDB地址列表
        List serverAddresses = new ArrayList<>();
        ServerAddress serverAddress = null;
        try {
            serverAddress = new ServerAddress(host, port);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        serverAddresses.add(serverAddress);

        System.out.println("serverAddresses:" + serverAddresses.toString());

        // 连接认证
        List mongoCredentialList = new ArrayList<>();
        if (username != null) {
            mongoCredentialList.add(MongoCredential.createScramSha1Credential(
                    username,
                    authenticationDatabase != null ? authenticationDatabase : database,
                    password.toCharArray()));
        }
        System.out.println("mongoCredentialList:" + mongoCredentialList.toString());

        //创建客户端和Factory
        MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredentialList, mongoClientOptions);
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, database);

        return mongoDbFactory;
    }
}
测试
  • 创建mongodb document bean类
package com.geneseeq.access.model;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.io.Serializable;


@Document(collection = "test")
public class BaseOrder implements Serializable {


    private static final long serialVersionUID = 77220451538889640L;

    @Field("_id")
    private String _id;

    @Field("id")
    private String id;
    @Field("user_name")
    private String userName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    private String passWord;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }
}
  • 实现操作mongodb service
package com.geneseeq.access.service.mongodb.impl;

import com.geneseeq.access.model.BaseOrder;
import com.geneseeq.access.service.mongodb.TestMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service("TestMongoService")
public class TestMongoServiceImpl implements TestMongoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveBaseOrder(BaseOrder baseOrder) {
        mongoTemplate.save(baseOrder);
    }

    @Override
    public void upsertOrder(BaseOrder baseOrder) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(baseOrder.get_id()));
        Update update = new Update();
        update.set("user_name", baseOrder.getUserName());
        update.set("id", baseOrder.getId());
//        update.set("passWord", baseOrder.getPassWord());
        mongoTemplate.upsert(query, update, BaseOrder.class);
    }
}
  • controller实现
package com.geneseeq.access.controller;

import com.geneseeq.access.GeneseeqAccessApplication;
import com.geneseeq.access.model.BaseOrder;
import com.geneseeq.access.service.mongodb.TestMongoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/test")
public class TestController {
    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private TestMongoService testMongoService;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public Object getOrder(HttpServletRequest request, HttpServletResponse response){
        try{
            BaseOrder baseOrder = new BaseOrder();
            baseOrder.set_id("1238");
            baseOrder.setId("gys");
            baseOrder.setPassWord("asfas");
            baseOrder.setUserName("ewqerq");
            //testMongoService.saveBaseOrder(baseOrder);
            testMongoService.upsertOrder(baseOrder);
            return baseOrder;
        } catch (Exception e){
            log.error("failed, error is: "+ e);
            return null;
        }
    }
}
  • 发送GET请求,url路径为:/test/info
  • 查看mongodb是否存在数据
{ "_id" : "1238", "user_name" : "ewqerq", "id" : "gys" }

你可能感兴趣的:(spring boot使用mongodb)