{"id":236813,"date":"2022-03-12T09:42:31","date_gmt":"2022-03-12T01:42:31","guid":{"rendered":"https:\/\/lrxjmw.cn\/?p=236813"},"modified":"2022-02-28T10:43:39","modified_gmt":"2022-02-28T02:43:39","slug":"mongodb-springboot-linux","status":"publish","type":"post","link":"https:\/\/lrxjmw.cn\/mongodb-springboot-linux.html","title":{"rendered":"\u6559\u4f60SpringBoot \u6574\u5408mongoDB\u5e76\u81ea\u5b9a\u4e49\u8fde\u63a5\u6c60"},"content":{"rendered":"\n\n\n
\u5bfc\u8bfb<\/td>\n\u8fd9\u7bc7\u6587\u7ae0\u4e3b\u8981\u4ecb\u7ecd\u4e86SpringBoot \u6574\u5408mongoDB\u5e76\u81ea\u5b9a\u4e49\u8fde\u63a5\u6c60 ,\u6574\u5408mongoDB\u7684\u76ee\u7684\u5c31\u662f\u60f3\u7528\u5b83\u7ed9\u6211\u4eec\u63d0\u4f9b\u7684mongoTemplate\uff0c\u5b83\u53ef\u4ee5\u5f88\u5bb9\u6613\u7684\u64cd\u4f5cmongoDB\u6570\u636e\u5e93\uff0c\u5bf9\u6574\u5408\u8fc7\u7a0b\u53ca\u5b9e\u4f8b\u4ee3\u7801\u611f\u5174\u8da3\u7684\u670b\u53cb\u8ddf\u968f\u5c0f\u7f16\u4e00\u8d77\u770b\u770b\u5427<\/strong><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

\u5f97\u529b\u4e8eSpringBoot\u7684\u7279\u6027\uff0c\u6574\u5408mongoDB\u662f\u5f88\u5bb9\u6613\u7684\uff0c\u6211\u4eec\u6574\u5408mongoDB\u7684\u76ee\u7684\u5c31\u662f\u60f3\u7528\u5b83\u7ed9\u6211\u4eec\u63d0\u4f9b\u7684mongoTemplate\uff0c\u5b83\u53ef\u4ee5\u5f88\u5bb9\u6613\u7684\u64cd\u4f5cmongoDB\u6570\u636e\u5e93\u3002<\/p>\n

\u4e3a\u4e86\u81ea\u5b9a\u4e49\u8fde\u63a5\u6c60\uff0c\u6211\u4eec\u5728\u914d\u7f6e\u7c7b\u4e2d\u4e3b\u8981\u4e0eMongoClientOptions\u3001MongoCredential\u3001MongoClient\u3001MongoDbFactory\u6253\u4ea4\u9053\u3002\u6700\u7ec8\u7684\u76ee\u7684\u5c31\u662f\u914d\u7f6e\u597d\u4e00\u4e2aMongoDbFactory\u7684bean\u4ea4\u7531Spring\u7ba1\u7406\u3002<\/p>\n

Maven \u4f9d\u8d56<\/strong><\/div>\n
\r\n    org.springframework.boot<\/groupid>\r\n    spring-boot-starter-data-mongodb<\/artifactid>\r\n<\/dependency>\r\n<\/pre>\n

\u914d\u7f6e\u6587\u4ef6<\/p>\n

\r\nmongodb:\r\n  database: bfa_mongo\r\n  username: \"xxx\"\r\n  password: \"xxxxx\"\r\n  address: \"host:port\"\r\n  authenticationDatabase: [\u8bbe\u7f6e\u4f60\u7684\u8ba4\u8bc1\u6570\u636e\u5e93\uff0c\u5982\u679c\u6709\u7684\u8bdd]\r\n  # \u8fde\u63a5\u6c60\u914d\u7f6e\r\n  clientName: ${spring.application.name} # \u5ba2\u6237\u7aef\u7684\u6807\u8bc6\uff0c\u7528\u4e8e\u5b9a\u4f4d\u8bf7\u6c42\u6765\u6e90\u7b49\r\n  connectionTimeoutMs: 10000     # TCP\u8fde\u63a5\u8d85\u65f6\uff0c\u6beb\u79d2\r\n  readTimeoutMs: 15000       # TCP\u8bfb\u53d6\u8d85\u65f6\uff0c\u6beb\u79d2\r\n  poolMaxWaitTimeMs: 3000        #\u5f53\u8fde\u63a5\u6c60\u65e0\u53ef\u7528\u8fde\u63a5\u65f6\u5ba2\u6237\u7aef\u963b\u585e\u7b49\u5f85\u7684\u65f6\u957f\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  connectionMaxIdleTimeMs: 60000   #TCP\u8fde\u63a5\u95f2\u7f6e\u65f6\u95f4\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  connectionMaxLifeTimeMs: 120000    #TCP\u8fde\u63a5\u6700\u591a\u53ef\u4ee5\u4f7f\u7528\u591a\u4e45\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  heartbeatFrequencyMs: 20000      #\u5fc3\u8df3\u68c0\u6d4b\u53d1\u9001\u9891\u7387\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  minHeartbeatFrequencyMs: 8000    #\u6700\u5c0f\u7684\u5fc3\u8df3\u68c0\u6d4b\u53d1\u9001\u9891\u7387\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  heartbeatConnectionTimeoutMs: 10000  #\u5fc3\u8df3\u68c0\u6d4bTCP\u8fde\u63a5\u8d85\u65f6\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  heartbeatReadTimeoutMs: 15000    #\u5fc3\u8df3\u68c0\u6d4bTCP\u8fde\u63a5\u8bfb\u53d6\u8d85\u65f6\uff0c\u5355\u4f4d\u6beb\u79d2\r\n  connectionsPerHost: 20       # \u6bcf\u4e2ahost\u7684TCP\u8fde\u63a5\u6570\r\n  minConnectionsPerHost: 5     #\u6bcf\u4e2ahost\u7684\u6700\u5c0fTCP\u8fde\u63a5\u6570\r\n  #\u8ba1\u7b97\u5141\u8bb8\u591a\u5c11\u4e2a\u7ebf\u7a0b\u963b\u585e\u7b49\u5f85\u53ef\u7528TCP\u8fde\u63a5\u65f6\u7684\u4e58\u6570\uff0c\u7b97\u6cd5\uff1athreadsAllowedToBlockForConnectionMultiplier*connectionsPerHost\uff0c\u5f53\u524d\u914d\u7f6e\u5141\u8bb810*20\u4e2a\u7ebf\u7a0b\u963b\u585e\r\n  threadsAllowedToBlockForConnectionMultiplier: 10<\/pre>\n

\u6ce8\u610f:\u5176\u4e2d\u7684address\u53c2\u6570\u53ef\u4ee5\u914d\u7f6e\u4e3a\u4e00\u4e2a\u6570\u7ec4\uff08\u4ee3\u8868\u96c6\u7fa4\u6a21\u5f0f\uff09<\/p>\n

address: \r\n   - \"host:port\"\r\n   - \"host2:port2\"<\/pre>\n
MongoConfig\u914d\u7f6e\u7c7b<\/strong><\/div>\n

\u914d\u7f6e\u7c7b\u4e2d\u4f7f\u7528\u4e86lombok\uff0c\u5982\u679c\u4f60\u6ca1\u6709\u7528lombok\u4f9d\u8d56\u548cIDE\u63d2\u4ef6\uff0c\u4f60\u8981\u91cd\u5199getter\u3001Setter\u65b9\u6cd5\uff1a<\/p>\n

\u4ee3\u7801\u7a0d\u957f\uff0c\u53ef\u4ee5\u590d\u5236\u5728IDEA\u4e2d\u67e5\u770b\uff1a<\/p>\n

\r\nimport com.mongodb.MongoClient;\r\nimport com.mongodb.MongoClientOptions;\r\nimport com.mongodb.MongoCredential;\r\nimport com.mongodb.ServerAddress;\r\nimport lombok.Getter;\r\nimport lombok.Setter;\r\nimport lombok.extern.slf4j.Slf4j;\r\nimport org.springframework.beans.factory.BeanFactory;\r\nimport org.springframework.boot.context.properties.ConfigurationProperties;\r\nimport org.springframework.boot.context.properties.EnableConfigurationProperties;\r\nimport org.springframework.context.annotation.Bean;\r\nimport org.springframework.context.annotation.Configuration;\r\nimport org.springframework.context.annotation.Primary;\r\nimport org.springframework.data.mongodb.MongoDbFactory;\r\nimport org.springframework.data.mongodb.core.SimpleMongoDbFactory;\r\nimport org.springframework.data.mongodb.core.convert.DbRefResolver;\r\nimport org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;\r\nimport org.springframework.data.mongodb.core.convert.MappingMongoConverter;\r\nimport org.springframework.data.mongodb.core.convert.MongoCustomConversions;\r\nimport org.springframework.data.mongodb.core.mapping.MongoMappingContext;\r\nimport org.springframework.validation.annotation.Validated;\r\n \r\nimport javax.validation.constraints.Min;\r\nimport javax.validation.constraints.NotNull;\r\nimport javax.validation.constraints.Size;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\n \r\n@Slf4j\r\n@Configuration\r\n@EnableConfigurationProperties(MongoConfig.MongoClientOptionProperties.class)\r\npublic class MongoConfig {\r\n \r\n    \/**\r\n     * monogo \u8f6c\u6362\u5668\r\n     * @return\r\n     *\/\r\n    @Bean\r\n    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,\r\n                                                       MongoMappingContext context, BeanFactory beanFactory, MongoCustomConversions conversions) {\r\n        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);\r\n        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);\r\n        \/\/ remove _class field\r\n\/\/    mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));\r\n        mappingConverter.setCustomConversions(conversions);\r\n        return mappingConverter;\r\n    }\r\n \r\n    \/**\r\n     * \u81ea\u5b9a\u4e49mongo\u8fde\u63a5\u6c60\r\n     * @param properties\r\n     * @return\r\n     *\/\r\n    @Bean\r\n    public MongoDbFactory mongoDbFactory(MongoClientOptionProperties properties) {\r\n        \/\/\u521b\u5efa\u5ba2\u6237\u7aef\u53c2\u6570\r\n        MongoClientOptions options = mongoClientOptions(properties);\r\n \r\n        \/\/\u521b\u5efa\u5ba2\u6237\u7aef\u548cFactory\r\n        List serverAddresses = new ArrayList<>();\r\n        for (String address : properties.getAddress()) {\r\n            String[] hostAndPort = address.split(\":\");\r\n            String host = hostAndPort[0];\r\n            Integer port = Integer.parseInt(hostAndPort[1]);\r\n            ServerAddress serverAddress = new ServerAddress(host, port);\r\n            serverAddresses.add(serverAddress);\r\n        }\r\n \r\n        \/\/\u521b\u5efa\u8ba4\u8bc1\u5ba2\u6237\u7aef\r\n        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUsername(),\r\n                properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),\r\n                properties.getPassword().toCharArray());\r\n \r\n        MongoClient mongoClient = new MongoClient(serverAddresses.get(0), mongoCredential, options);\r\n        \/\/\u96c6\u7fa4\u6a21\u5f0f\r\n        if (serverAddresses.size() > 1) {\r\n            mongoClient = new MongoClient(serverAddresses, new ArrayList<>(Arrays.asList(mongoCredential)));\r\n        }\r\n        \/** ps: \u521b\u5efa\u975e\u8ba4\u8bc1\u5ba2\u6237\u7aef*\/\r\n        \/\/MongoClient mongoClient = new MongoClient(serverAddresses, mongoClientOptions);\r\n        return new SimpleMongoDbFactory(mongoClient, properties.getDatabase());\r\n    }\r\n \r\n    \/**\r\n     * mongo\u5ba2\u6237\u7aef\u53c2\u6570\u914d\u7f6e\r\n     * @return\r\n     *\/\r\n    public MongoClientOptions mongoClientOptions(MongoClientOptionProperties properties) {\r\n        return MongoClientOptions.builder()\r\n                .connectTimeout(properties.getConnectionTimeoutMs())\r\n                .socketTimeout(properties.getReadTimeoutMs()).applicationName(properties.getClientName())\r\n                .heartbeatConnectTimeout(properties.getHeartbeatConnectionTimeoutMs())\r\n                .heartbeatSocketTimeout(properties.getHeartbeatReadTimeoutMs())\r\n                .heartbeatFrequency(properties.getHeartbeatFrequencyMs())\r\n                .minHeartbeatFrequency(properties.getMinHeartbeatFrequencyMs())\r\n                .maxConnectionIdleTime(properties.getConnectionMaxIdleTimeMs())\r\n                .maxConnectionLifeTime(properties.getConnectionMaxLifeTimeMs())\r\n                .maxWaitTime(properties.getPoolMaxWaitTimeMs())\r\n                .connectionsPerHost(properties.getConnectionsPerHost())\r\n                .threadsAllowedToBlockForConnectionMultiplier(\r\n                        properties.getThreadsAllowedToBlockForConnectionMultiplier())\r\n                .minConnectionsPerHost(properties.getMinConnectionsPerHost()).build();\r\n    }\r\n \r\n    @Getter\r\n    @Setter\r\n    @Validated\r\n    @ConfigurationProperties(prefix = \"mongodb\")\r\n    public static class MongoClientOptionProperties {\r\n \r\n        \/** \u57fa\u7840\u8fde\u63a5\u53c2\u6570 *\/\r\n        private String database;\r\n        private String username;\r\n        private String password;\r\n        @NotNull\r\n        private List address;\r\n        private String authenticationDatabase;\r\n \r\n        \/** \u5ba2\u6237\u7aef\u8fde\u63a5\u6c60\u53c2\u6570 *\/\r\n        @NotNull\r\n        @Size(min = 1)\r\n        private String clientName;\r\n        \/** socket\u8fde\u63a5\u8d85\u65f6\u65f6\u95f4 *\/\r\n        @Min(value = 1)\r\n        private int connectionTimeoutMs;\r\n        \/** socket\u8bfb\u53d6\u8d85\u65f6\u65f6\u95f4 *\/\r\n        @Min(value = 1)\r\n        private int readTimeoutMs;\r\n        \/** \u8fde\u63a5\u6c60\u83b7\u53d6\u94fe\u63a5\u7b49\u5f85\u65f6\u95f4 *\/\r\n        @Min(value = 1)\r\n        private int poolMaxWaitTimeMs;\r\n        \/** \u8fde\u63a5\u95f2\u7f6e\u65f6\u95f4 *\/\r\n        @Min(value = 1)\r\n        private int connectionMaxIdleTimeMs;\r\n        \/** \u8fde\u63a5\u6700\u591a\u53ef\u4ee5\u4f7f\u7528\u591a\u4e45 *\/\r\n        @Min(value = 1)\r\n        private int connectionMaxLifeTimeMs;\r\n        \/** \u5fc3\u8df3\u68c0\u6d4b\u53d1\u9001\u9891\u7387 *\/\r\n        @Min(value = 2000)\r\n        private int heartbeatFrequencyMs;\r\n \r\n        \/** \u6700\u5c0f\u7684\u5fc3\u8df3\u68c0\u6d4b\u53d1\u9001\u9891\u7387 *\/\r\n        @Min(value = 300)\r\n        private int minHeartbeatFrequencyMs;\r\n        \/** \u8ba1\u7b97\u5141\u8bb8\u591a\u5c11\u4e2a\u7ebf\u7a0b\u963b\u585e\u7b49\u5f85\u65f6\u7684\u4e58\u6570\uff0c\u7b97\u6cd5\uff1athreadsAllowedToBlockForConnectionMultiplier*connectionsPerHost *\/\r\n        @Min(value = 1)\r\n        private int threadsAllowedToBlockForConnectionMultiplier;\r\n        \/** \u5fc3\u8df3\u68c0\u6d4b\u8fde\u63a5\u8d85\u65f6\u65f6\u95f4 *\/\r\n        @Min(value = 200)\r\n        private int heartbeatConnectionTimeoutMs;\r\n        \/** \u5fc3\u8df3\u68c0\u6d4b\u8bfb\u53d6\u8d85\u65f6\u65f6\u95f4 *\/\r\n        @Min(value = 200)\r\n        private int heartbeatReadTimeoutMs;\r\n \r\n        \/** \u6bcf\u4e2ahost\u6700\u5927\u8fde\u63a5\u6570 *\/\r\n        @Min(value = 1)\r\n        private int connectionsPerHost;\r\n        \/** \u6bcf\u4e2ahost\u7684\u6700\u5c0f\u8fde\u63a5\u6570 *\/\r\n        @Min(value = 1)\r\n        private int minConnectionsPerHost;\r\n    }\r\n}<\/string><\/serveraddress><\/pre>\n

MappingMongoConverter\u53ef\u4ee5\u81ea\u5b9a\u4e49mongo\u8f6c\u6362\u5668\uff0c\u4e3b\u8981\u81ea\u5b9a\u4e49\u5b58\u53d6mongo\u6570\u636e\u65f6\u7684\u4e00\u4e9b\u64cd\u4f5c\uff0c\u4f8b\u5982 mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null)) \u65b9\u6cd5\u4f1a\u5c06mongo\u6570\u636e\u4e2d\u7684_class\u5b57\u6bb5\u53bb\u6389\u3002<\/p>\n

\u6700\u540e\u901a\u8fc7 new SimpleMongoDbFactory(mongoClient, properties.getDatabase())\u65b9\u6cd5\u914d\u7f6e\u4e86\u4e00\u4e2aMongoDbFactory\u4ea4\u7531Spring\u7ba1\u7406\uff0cSpringboot\u4f1a\u62ff\u8fd9\u4e2aMongoDbFactory\u5de5\u5382bean\u6765new\u4e00\u4e2aMongoTemplate\uff0c\u5728MongoDbFactoryDependentConfiguration\u7c7b\u4e0b\u53ef\u4ee5\u770b\u5230SpringBoot\u5e2e\u4f60\u505a\u5f97\u4e8b\uff1a<\/p>\n

\r\n\/**\r\n * Configuration for Mongo-related beans that depend on a {@link MongoDbFactory}.\r\n *\r\n * @author Andy Wilkinson\r\n *\/\r\n@Configuration\r\n@ConditionalOnBean(MongoDbFactory.class)\r\nclass MongoDbFactoryDependentConfiguration {\r\n \r\n    private final MongoProperties properties;\r\n    MongoDbFactoryDependentConfiguration(MongoProperties properties) {\r\n        this.properties = properties;\r\n    }\r\n     \r\n    \/\/SpringBoot\u521b\u5efaMongoTemplate\u5b9e\u4f8b\r\n    @Bean\r\n    @ConditionalOnMissingBean\r\n    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter converter) {\r\n        return new MongoTemplate(mongoDbFactory, converter);\r\n    @ConditionalOnMissingBean(MongoConverter.class)\r\n    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,\r\n            MongoCustomConversions conversions) {\r\n        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);\r\n        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);\r\n        mappingConverter.setCustomConversions(conversions);\r\n        return mappingConverter;\r\n     \r\n    \/\/...\r\n}<\/pre>\n

SpringBoot\u5229\u7528\u6211\u4eec\u914d\u7f6e\u597d\u7684MongoDbFactory\u5728\u914d\u7f6e\u7c7b\u4e2d\u751f\u6210\u4e00\u4e2aMongoTemplate\uff0c\u4e4b\u540e\u6211\u4eec\u5c31\u53ef\u4ee5\u5728\u9879\u76ee\u4ee3\u7801\u4e2d\u76f4\u63a5@Autowired\u4e86\u3002\u56e0\u4e3a\u7528\u4e8e\u751f\u6210MongoTemplate\u7684MongoDbFactory\u662f\u6211\u4eec\u81ea\u5df1\u5728MongoConfig\u914d\u7f6e\u7c7b\u4e2d\u751f\u6210\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u81ea\u5b9a\u4e49\u7684\u8fde\u63a5\u6c60\u53c2\u6570\u4e5f\u5c31\u751f\u6548\u4e86\u3002<\/p>\n

\u5230\u6b64\u8fd9\u7bc7\u5173\u4e8eSpringBoot \u6574\u5408mongoDB\u5e76\u81ea\u5b9a\u4e49\u8fde\u63a5\u6c60\u7684\u6587\u7ae0\u5c31\u4ecb\u7ecd\u5230\u8fd9\u4e86\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"

\u5f97\u529b\u4e8eSpringBoot\u7684\u7279\u6027\uff0c\u6574\u5408mongoDB\u662f\u5f88\u5bb9\u6613\u7684\uff0c\u6211\u4eec\u6574\u5408mongoDB\u7684\u76ee\u7684\u5c31\u662f\u60f3\u7528\u5b83\u7ed9\u6211\u4eec\u63d0 […]<\/p>\n","protected":false},"author":668,"featured_media":163508,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[55],"tags":[],"class_list":["post-236813","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-thread"],"acf":[],"_links":{"self":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts\/236813","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/users\/668"}],"replies":[{"embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/comments?post=236813"}],"version-history":[{"count":6,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts\/236813\/revisions"}],"predecessor-version":[{"id":236820,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/posts\/236813\/revisions\/236820"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/media\/163508"}],"wp:attachment":[{"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/media?parent=236813"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/categories?post=236813"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lrxjmw.cn\/wp-json\/wp\/v2\/tags?post=236813"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}