当先锋百科网

首页 1 2 3 4 5 6 7

关于mongodb的安装与linux命令不在描述(个人建议先熟悉mongoDb的命令)

1,导入maven依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

springboot版本 2.0.4.RELEASE

配置类(一 简略版本)

@Configuration
public class MongoDBSimpleConfig {

    private final String url = "mongodb://root:[email protected]:27017/?authSource=admin";
    private final String db = "zhangmr";
    @Bean
    public MongoDbFactory mongoDbFactory(){
        MongoClientURI mongoClientURI = new MongoClientURI(url);
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        return new SimpleMongoDbFactory(mongoClient,db);
    }
    @Bean
    public MongoTemplate getMongoTemplate() {
        return new MongoTemplate(mongoDbFactory());
    }

}

2.配置(二 带客户端连接池 )(若不需要配置客户端数据源可以注释相关配置)

# mongodb-配置
#要连接的数据库
mongodb.database=zhangmr
#spring.data.mongodb.uri=mongodb://139.224.43.3:27017/测试
#用户名
mongodb.username=root
#spring.data.mongodb.username=root
#密码
mongodb.password=root
#spring.data.mongodb.password=root
#IP和端口(host:port),例如127.0.0.1:27017。集群模式用,分隔开,例如host1:port1,host2:port2
mongodb.servers=127.0.0.1:27017
#设置认证数据库,如果有的话
mongodb.authenticationDatabase=admin
# 客户端连接池参数
#客户端的标识,用于定位请求来源等,一般用程序名
# mongodb.clientName=${spring.application.name}
#TCP(socket)连接超时时间,毫秒
mongodb.connectionTimeoutMs=5000
#TCP(socket)连接闲置时间,毫秒
mongodb.maxConnectionIdleTimeMs=60000
#TCP(socket)连接最多可以使用多久,毫秒
mongodb.maxConnectionLifeTimeMs=300000
#TCP(socket)读取超时时间,毫秒
mongodb.readTimeoutMs=15000
#当连接池无可用连接时客户端阻塞等待的最大时长,毫秒
mongodb.maxWaitTimeMs=5000
#心跳检测发送频率,毫秒
mongodb.heartbeatFrequencyMs=20000
#最小的心跳检测发送频率,毫秒
mongodb.minHeartbeatFrequencyMs=8000
#心跳检测连接超时时间,毫秒
mongodb.heartbeatConnectionTimeoutMs=10000
#心跳检测读取超时时间,毫秒
mongodb.heartbeatReadTimeoutMs=15000
#线程池允许的最大连接数
mongodb.connectionsPerHost=100
#线程池空闲时保持的最小连接数
mongodb.minConnectionsPerHost=20
#计算允许多少个线程阻塞等待时的乘数,算法:threadsAllowedToBlockForConnectionMultiplier*maxConnectionsPerHost
mongodb.threadsAllowedToBlockForConnectionMultiplier=10
@Configuration
public class MongoDBConfig {
    @Value("${mongodb.servers}")
    private String servers; //IP和端口(host:port),例如127.0.0.1:27017。集群模式用,分隔开,例如host1:port1,host2:port2
    @Value("${mongodb.username}")
    private String username; //用户名
    @Value("${mongodb.password}")
    private String password; //密码
    @Value("${mongodb.database}")
    private String database; //要连接的数据库
    @Value("${mongodb.authenticationDatabase}")
    private String authenticationDatabase;  //认证用户的数据库

    @Value("${mongodb.connectionTimeoutMs}")
    private int connectionTimeoutMs;  //连接超时时间 毫秒
    @Value("${mongodb.maxConnectionIdleTimeMs}")
    private int maxConnectionIdleTimeMs; //连接闲置时间 毫秒
    @Value("${mongodb.maxConnectionLifeTimeMs}")
    private int maxConnectionLifeTimeMs; //连接最多可以使用多久 毫秒
    @Value("${mongodb.readTimeoutMs}")
    private int readTimeoutMs; //读取超时时间 毫秒
    @Value("${mongodb.maxWaitTimeMs}")
    private int maxWaitTimeMs; //当连接池无可用连接时客户端阻塞等待的最大时长 毫秒
    @Value("${mongodb.heartbeatFrequencyMs}")
    private int heartbeatFrequencyMs; //心跳检测发送频率 毫秒
    @Value("${mongodb.minHeartbeatFrequencyMs}")
    private int minHeartbeatFrequencyMs; //最小的心跳检测发送频率 毫秒
    @Value("${mongodb.heartbeatConnectionTimeoutMs}")
    private int heartbeatConnectionTimeoutMs; //心跳检测连接超时时间 毫秒
    @Value("${mongodb.heartbeatReadTimeoutMs}")
    private int heartbeatReadTimeoutMs; //心跳检测读取超时时间 毫秒
    @Value("${mongodb.connectionsPerHost}")
    private int connectionsPerHost; //线程池允许的最大连接数
    @Value("${mongodb.minConnectionsPerHost}")
    private int minConnectionsPerHost; //线程池空闲时保持的最小连接数
    @Value("${mongodb.threadsAllowedToBlockForConnectionMultiplier}")
    private int threadsAllowedToBlockForConnectionMultiplier; //计算允许多少个线程阻塞等待时的乘数,算法:threadsAllowedToBlockForConnectionMultiplier*maxConnectionsPerHost

    //MongoClientOptions

    /**
     * 此Bean也是可以不显示定义的,如果我们没有显示定义生成MongoTemplate实例,
     * SpringBoot利用我们配置好的MongoDbFactory在配置类中生成一个MongoTemplate,
     * 之后我们就可以在项目代码中直接@Autowired了。因为用于生成MongoTemplate
     * 的MongoDbFactory是我们自己在MongoConfig配置类中生成的,所以我们自定义的连接池参数也就生效了。
     *
     * @param mongoDbFactory mongo工厂
     * @param converter      转换器
     * @return MongoTemplate实例
     */
    @Bean
    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MappingMongoConverter converter) {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
        // 设置读从库优先
        mongoTemplate.setReadPreference(ReadPreference.secondaryPreferred());
        return mongoTemplate;
    }

    /**
     * 转换器
     * MappingMongoConverter可以自定义mongo转换器,主要自定义存取mongo数据时的一些操作,例如 mappingConverter.setTypeMapper(new
     * DefaultMongoTypeMapper(null)) 方法会将mongo数据中的_class字段去掉。
     *
     * @param factory     mongo工厂
     * @param context     上下文
     * @param conversions 自定义转换器
     * @return 转换器对象
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,
                                                       MongoCustomConversions conversions) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        mappingConverter.setCustomConversions(conversions);
        // remove _class field
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }

    /**
     * 自定义mongo连接池
     *
     * @return MongoDbFactory对象
     */
    @Bean
    public MongoDbFactory mongoDbFactory() {

        MongoClient mongoClient;

        // 创建客户端参数
        MongoClientOptions mongoClientOptions = mongoClientOptions();

        // 解析获取mongo服务地址
        List<ServerAddress> serverAddressList = getServerAddress(servers);

        // 创建认证
        MongoCredential mongoCredential = getCredential();

        // 创建客户端
        if (null == mongoCredential) {
            mongoClient = new MongoClient(serverAddressList, mongoClientOptions);
        } else {
            mongoClient = new MongoClient(serverAddressList, mongoCredential, mongoClientOptions);
        }

        return new SimpleMongoDbFactory(mongoClient, database);
    }
    /**
     * 创建认证
     *
     * @return 认证对象
     */
    private MongoCredential getCredential() {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 没有专用认证数据库则取当前数据库
            String authDatabase = StringUtils.isEmpty(authenticationDatabase) ?
                    database : authenticationDatabase;
            return MongoCredential.createCredential(username, authDatabase,password.toCharArray());
        }
        return null;
    }

    /**
     * 获取数据库服务地址
     *
     * @param mongoAddress 地址字符串
     * @return 服务地址数组
     */
    private List<ServerAddress> getServerAddress(String mongoAddress) {
        String[] mongoAddressArray = mongoAddress.trim().split(",");
        List<ServerAddress> serverAddressList = new ArrayList<>();
        for (String address : mongoAddressArray) {
            String[] hostAndPort = address.split(":");
            serverAddressList.add(new ServerAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1])));
        }
        return serverAddressList;
    }

    /**
     * mongo客户端参数配置
     *
     * @return mongo客户端参数配置对象
     */
    private MongoClientOptions mongoClientOptions() {
        return MongoClientOptions.builder().connectTimeout(connectionTimeoutMs)
                .maxConnectionIdleTime(maxConnectionIdleTimeMs)
                .maxConnectionLifeTime(maxConnectionLifeTimeMs)
                .socketTimeout(readTimeoutMs)
                .maxWaitTime(maxWaitTimeMs)
                .heartbeatFrequency(heartbeatFrequencyMs)
                .minHeartbeatFrequency(minHeartbeatFrequencyMs)
                .heartbeatConnectTimeout(heartbeatConnectionTimeoutMs)
                .heartbeatSocketTimeout(heartbeatReadTimeoutMs)
                .connectionsPerHost(connectionsPerHost)
                .minConnectionsPerHost(minConnectionsPerHost)
                .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier)
                .readPreference(ReadPreference.secondaryPreferred())
                .build();
    }
}

3.测试结果

package com.zhangmr;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.zhangmr.rabbit.provider.MyProvider;
import org.bson.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class ThreadApplicationTests {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Test
    public void contextLoadsMongo() {
        MongoDatabase db = mongoTemplate.getDb();
        MongoCollection<Document> collection = db.getCollection("zhangmr");
        FindIterable<Document> documents = collection.find();
        List<String> list = new ArrayList<>();
        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()){
            list.add(iterator.next().toJson());
        }
        System.out.println(list);
    }

}

在这里插入图片描述
在这里插入图片描述