Springboot中的HikariCP for MongoDB

时间:2018-12-04 13:41:38

标签: mongodb spring-boot hikaricp

我正在寻找在Springboot中为mongoDB创建一个连接池。我目前正在使用Springdata Mongo存储库连接数据库和集合,但不确定如何创建数据池连接

这是当前的实现方式

PersonRepository.java

package com.test.TestAPI.repository;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.test.TestAPI.dto.Person;

@Repository
public interface PersonRepository extends MongoRepository<Person, String> {


}

PersonService

package com.test.TestAPI.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;

@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepo;

    public List<Person> findAllPersons() {
        return personRepo.findAll();
    }

    public Person createPerson(Person person) {
        return personRepo.save(person);
    }

}

PersonController

package com.test.TestAPI.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.test.TestAPI.service.impl.PersonService;
import com.test.TestAPI.dto.Person;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(path="/v1/personController")
@Api(value="Controller for Person document")
public class PersonController {

    @Autowired
    PersonService service;

    @GetMapping("/getAllPersons")
    @ApiOperation(produces = MediaType.APPLICATION_JSON_VALUE, httpMethod = "GET", response = List.class, 
            value = "getAllPersons from the database", notes = "Sample note")
    public ResponseEntity<List<Person>> getAllPersons(){
        List<Person> personList = service.findAllPersons();
        return new ResponseEntity<List<Person>>(personList, HttpStatus.OK);
    }
}

SimpleCommandLineConfig

package com.test.TestAPI.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Component;

import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;


@Component
@Order(3)
public class SimpleCommandLineConfig implements CommandLineRunner {

    @Autowired
    PersonRepository repo;

    @Override
    public void run(String... args) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("third command line runner");
        System.out.println(repo.save(new Person("rr","rr",4)));
    }

}

App.java

package com.test.TestAPI.main;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@ComponentScan(basePackages= {"com.test.TestAPI"})
@EnableMongoRepositories(basePackages= {"com.test.TestAPI.repository"})
public class App 
{
     public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

}

此外,我想知道像MongoDB的自定义存储库这样的spring数据存储库是否负责连接池机制?在这种情况下,连接池如何发生?您能帮我吗

1 个答案:

答案 0 :(得分:0)

我想我找到了答案。就像我们为RDBMS使用JDBC模板来存储数据库一样,spring提供了一个称为MongoTemplates的东西,它基于给定的db配置形成了一个连接池

这是示例实现

MongoClientFactory.java

StackedWidgets

DataSourceConfig.java(另一个配置类。相同的配置类也可以用于定义所有bean)

 public @Bean MongoClientFactoryBean mongo() throws Exception {
              MongoClientFactoryBean mongo = new MongoClientFactoryBean();
              mongo.setHost("localhost");
              MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
                      .connectionsPerHost(2000)
                      .connectTimeout(4000)
                      //.maxConnectionIdleTime(1000000000)
                      .maxWaitTime(3000)
                      .retryWrites(true)
                      .socketTimeout(4000)
                      .sslInvalidHostNameAllowed(true)//this is very risky

                      .build();
              mongo.setMongoClientOptions(clientOptions);


              return mongo;
         }

现在可以自动连接您实现或服务中的模板/ mongoOperations并使用它

package com.fmr.FeedBackAPI.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;


@Configuration
@Import(value=MongoClientFactory.class)
public class DataSourceConfig {

    @Autowired
    Mongo mongo;

    @Autowired
    Environment env;

    @Bean
    public String test() {
        System.out.println("mongo"+mongo);
        return "rer";
    }


    private MongoTemplate mongoTemplate() {


        MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
        MongoTemplate template = new MongoTemplate(factory);

        return template;
    }

    @Bean
    @Qualifier(value="customMongoOps")
    public MongoOperations mongoOps() {
        MongoOperations ops = mongoTemplate();
        return ops;
    }


    @Bean
    public MongoDbFactory factory() {
        MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
        return factory;
    }

//  @Bean
//  public GridFsTemplate gridFsTemplate() {
//      return new GridFsTemplate(mongo, converter)
//  }

    @Bean
    public javax.sql.DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setMaximumPoolSize(100);
      //  ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
       // ds.setJdbcUrl(env.getProperty("spring.datasource.url"));;
        //ds.setUsername(env.getProperty("spring.datasource.username"));
        //ds.setPassword(env.getProperty("spring.datasource.password"));
        ds.addDataSourceProperty("cachePrepStmts", true);
        ds.addDataSourceProperty("prepStmtCacheSize", 250);
        ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
        ds.addDataSourceProperty("useServerPrepStmts", true);
        return ds;
    }
}

这是application.properties(这是在本地运行的默认实例)

package com.fmr.FeedBackAPI.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.fmr.FeedBackAPI.dto.ConfigDTO;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;


@Service
public class PlanConfigService {

    @Autowired
    @Qualifier(value="customMongoOps")
    MongoOperations mongoOps;

    public List<ConfigDTO> createConfigDTOList(List<ConfigDTO> configDTOList) {
        List<ConfigDTO> configList = new ArrayList<>();
        if(!mongoOps.collectionExists(ConfigDTO.class)) {
            mongoOps.createCollection("ConfigDTO_table");

        }
        //create the configDTOList
        mongoOps.insert(configDTOList, ConfigDTO.class);
        configList = mongoOps.findAll(ConfigDTO.class, "ConfigDTO_table");
        return configList;
    }

    public List<ConfigDTO> createConfigDTO(ConfigDTO configDTO) {
        List<ConfigDTO> configList = new ArrayList<>();
        if(!mongoOps.collectionExists(ConfigDTO.class)) {

            mongoOps.createCollection("ConfigDTO_table");

        }
        //create the configDTOList
         mongoOps.save(configDTO);

        configList = mongoOps.find(query(where("planId").is(configDTO.getPlanId())), ConfigDTO.class,"ConfigDTO_table");
        return configList;
    }
}