springboot啟動(dòng)mongoDB報(bào)錯(cuò)之禁用mongoDB自動(dòng)配置問題
springboot啟動(dòng)mongoDB報(bào)錯(cuò)之禁用mongoDB自動(dòng)配置
錯(cuò)誤信息如下:
springboot自動(dòng)配置了支持mongodb。
在啟動(dòng)springboot時(shí)會(huì)自動(dòng)實(shí)例化一個(gè)mongo實(shí)例。
所以自己配置的話,需要禁用掉springboot的自動(dòng)配置。
@SpringBootApplication(exclude = {MongoAutoConfiguration.class,MongoDataAutoConfiguration.class})
這個(gè)注解可以禁用springboot自帶的配置。
如下圖:
springboot整合MongoDB時(shí)碰到的問題
1.賬號(hào)總是不對(duì),導(dǎo)致查不出數(shù)據(jù),報(bào)錯(cuò)Auth…權(quán)鑒錯(cuò)誤
這次,我也是第一次接觸MongoDB,非常的生疏
springboot整合MongoDB,要在properties文件中配置賬號(hào)
mongodb基本語法:
use DATABASE_NAME; --創(chuàng)建數(shù)據(jù)庫 show dbs; --查看我們所有的庫,注意,我們剛創(chuàng)建的庫,如果沒有數(shù)據(jù),是不會(huì)被顯示的 show users; --查看當(dāng)前庫所有擁有的賬號(hào) db.createCollection(name, options) --在當(dāng)前數(shù)據(jù)庫中創(chuàng)建集合 show tables --查看當(dāng)前庫中有哪些集合 --在當(dāng)前數(shù)據(jù)庫中創(chuàng)建用戶并設(shè)置密碼及權(quán)限 db.createUser( ... { ... user : "aaa", ... pwd : "123456", ... roles: [ { role : "readWrite", db : "springboot" }] ... } ... )
通過上面的基礎(chǔ)鋪墊:
1.首先我們要登錄MongoDB數(shù)據(jù)庫
用管理員權(quán)限運(yùn)行cmd
進(jìn)入我們安裝的MongoDB的bin目錄下執(zhí)行命令
mongo
即可登錄MongoDB數(shù)據(jù)庫
2.創(chuàng)建數(shù)據(jù)庫
use springboot;
3.創(chuàng)建數(shù)據(jù)庫對(duì)應(yīng)的賬號(hào)
創(chuàng)建一個(gè)springboot賬號(hào),對(duì)springboot數(shù)據(jù)庫擁有讀寫權(quán)限
db.createUser( ... { ... user : "springboot", ... pwd : "123456", ... roles: [ { role : "readWrite", db : "springboot" }] ... } ... )
4.在springboot庫中創(chuàng)建集合user
db.createCollection("user"); --創(chuàng)建集合user show tables; --查看當(dāng)前庫中所有的集合 --- 并給集合user添加一條數(shù)據(jù) db.user.insert({ "user_name":"pzj", "note":"用戶pzj", "roles":[{ "role_name": "vip_user", "note": "會(huì)員" }] })
到此,MongoDB的數(shù)據(jù)庫初始化完成。
2.springboot工程代碼中的配置
主要說下properties中的配置,pom里面引入的包我就不說了
spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.username=springboot spring.data.mongodb.password=123456 spring.data.mongodb.database=springboot spring.data.mongodb.port=27017 logging.level.org.springframework.data.mongodb.core=DEBUG
3.查詢時(shí)遇見的錯(cuò)誤
No converter found capable of converting from org.bson.types.ObjectId to type Long異常
這個(gè)問題很好解決
我們?cè)趧?chuàng)建實(shí)體類對(duì)應(yīng)數(shù)據(jù)庫中的集合user時(shí),把id設(shè)置成了Long型,導(dǎo)致的報(bào)錯(cuò)
我們只要把id類型改成String即可。
在MongoDb里要求每個(gè)文檔都需要有_id 字段,java類中有如下情況會(huì)被映射為_id字段
如果1個(gè)字段加上了 @Id (org.springframework.data.annotation.Id)注解,那么將bean保存到數(shù)據(jù)庫時(shí)就會(huì)把該字段映射為文檔中的_id字段
如果java對(duì)象中沒有 @Id 注解,名字為id 的字段將會(huì)被映射為文檔中的_id字段
所以,也可以看出,我們的MongoDB數(shù)據(jù),是不需要我們?nèi)藶榈奶砑又麈Iid字段的
這個(gè)和以往的mysq等關(guān)系型數(shù)據(jù)庫有所不同
它會(huì)自動(dòng)給我們生成一個(gè)_id字段,作為集合的主鍵,標(biāo)識(shí)一條數(shù)據(jù)
我的操作記錄:
Microsoft Windows [版本 10.0.17134.81] (c) 2018 Microsoft Corporation。保留所有權(quán)利。 C:\WINDOWS\system32>mongo -port 27017 -u "admin" -p "123456" --authenticationDatabas Error parsing command line: unrecognised option '--authenticationDatabas' try 'mongo --help' for more information C:\WINDOWS\system32>d: D:\>cd MongoDB D:\MongoDB>cd Server D:\MongoDB\Server>cd 4.2 D:\MongoDB\Server\4.2>cd bin D:\MongoDB\Server\4.2\bin>mongo -port 27017 -u "admin" -p "123456" --authenticationDatabas Error parsing command line: unrecognised option '--authenticationDatabas' try 'mongo --help' for more information D:\MongoDB\Server\4.2\bin>mongo -port 27017 -u "admin" -p "123456" MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("92832542-8eb8-4df5-942b-671ae8e574f5") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > use admin switched to db admin > show users { "_id" : "admin.admin", "userId" : UUID("ee717096-e66e-4554-95a5-29aafd999c86"), "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > exit bye D:\MongoDB\Server\4.2\bin>mongo MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("37edcce7-3eea-430a-9dca-7bf84fa70e88") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > use admin switched to db admin > > db.auth("admin","123456") 1 > show users; { "_id" : "admin.admin", "userId" : UUID("ee717096-e66e-4554-95a5-29aafd999c86"), "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > exit bye D:\MongoDB\Server\4.2\bin>use admin 'use' 不是內(nèi)部或外部命令,也不是可運(yùn)行的程序 或批處理文件。 D:\MongoDB\Server\4.2\bin>mongo MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("25bd7adc-50a0-455c-af5d-48ad740ff1a4") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > use admin switched to db admin > db.auth("root","123456") Error: Authentication failed. 0 > exit bye D:\MongoDB\Server\4.2\bin>mongod --shutdown --dbpath=D:\MongodbData\db Error parsing command line: unrecognised option '--shutdown' try 'mongod --help' for more information D:\MongoDB\Server\4.2\bin>mongod --help Options: --networkMessageCompressors arg (=snappy,zstd,zlib) Comma-separated list of compressors to use for network messages General options: -h [ --help ] Show this usage information --version Show version information -f [ --config ] arg Configuration file specifying additional options --configExpand arg Process expansion directives in config file (none, exec, rest) --ipv6 Enable IPv6 support (disabled by default) --listenBacklog arg (=2147483647) Set socket listen backlog size --maxConns arg (=1000000) Max number of simultaneous connections --pidfilepath arg Full path to pidfile (if not set, no pidfile is created) --timeZoneInfo arg Full path to time zone info directory, e.g. /usr/share/zoneinfo -v [ --verbose ] [=arg(=v)] Be more verbose (include multiple times for more verbosity e.g. -vvvvv) --quiet Quieter output --port arg Specify port number - 27017 by default --logpath arg Log file to send write to instead of stdout - has to be a file, not directory --logappend Append to logpath instead of over-writing --logRotate arg Set the log rotation behavior (rename|reopen) --timeStampFormat arg Desired format for timestamps in log messages. One of ctime, iso8601-utc or iso8601-local --setParameter arg Set a configurable parameter --bind_ip arg Comma separated list of ip addresses to listen on - localhost by default --bind_ip_all Bind to all ip addresses --noauth Run without security --transitionToAuth For rolling access control upgrade. Attempt to authenticate over outgoing connections and proceed regardless of success. Accept incoming connections with or without authentication. --slowms arg (=100) Value of slow for profile and console log --slowOpSampleRate arg (=1) Fraction of slow ops to include in the profile and console log --auth Run with security --clusterIpSourceWhitelist arg Network CIDR specification of permitted origin for `__system` access --profile arg 0=off 1=slow, 2=all --cpu Periodically show cpu and iowait utilization --sysinfo Print some diagnostic system information --noscripting Disable scripting engine --notablescan Do not allow table scans --keyFile arg Private key for cluster authentication --clusterAuthMode arg Authentication mode used for cluster authentication. Alternatives are (keyFile|sendKeyFile|sendX509|x509) Replication options: --oplogSize arg Size to use (in MB) for replication op log. default is 5% of disk space (i.e. large is good) Replica set options: --replSet arg arg is <setname>[/<optionalseedhostlist >] --enableMajorityReadConcern [=arg(=1)] (=1) Enables majority readConcern Sharding options: --configsvr Declare this is a config db of a cluster; default port 27019; default dir /data/configdb --shardsvr Declare this is a shard db of a cluster; default port 27018 Storage options: --storageEngine arg What storage engine to use - defaults to wiredTiger if no data files present --dbpath arg Directory for datafiles - defaults to \data\db\ which is D:\data\db\ based on the current working drive --directoryperdb Each database will be stored in a separate directory --syncdelay arg (=60) Seconds between disk syncs (0=never, but not recommended) --journalCommitInterval arg (=100) how often to group/batch commit (ms) --noIndexBuildRetry Do not retry any index builds that were interrupted by shutdown --upgrade Upgrade db if needed --repair Run repair on all dbs --journal Enable journaling --nojournal Disable journaling (journaling is on by default for 64 bit) Free Monitoring Options: --enableFreeMonitoring arg Enable Cloud Free Monitoring (on|runtime|off) --freeMonitoringTag arg Cloud Free Monitoring Tags WiredTiger options: --wiredTigerCacheSizeGB arg Maximum amount of memory to allocate for cache; Defaults to 1/2 of physical RAM --wiredTigerJournalCompressor arg (=snappy) Use a compressor for log records [none|snappy|zlib|zstd] --wiredTigerDirectoryForIndexes Put indexes and data in different directories --wiredTigerMaxCacheOverflowFileSizeGB arg (=0) Maximum amount of disk space to use for cache overflow; Defaults to 0 (unbounded) --wiredTigerCollectionBlockCompressor arg (=snappy) Block compression algorithm for collection data [none|snappy|zlib|zstd] --wiredTigerIndexPrefixCompression arg (=1) Use prefix compression on row-store leaf pages TLS Options: --tlsOnNormalPorts Use TLS on configured ports --tlsMode arg Set the TLS operation mode (disabled|allowTLS|preferTLS|requireTLS ) --tlsCertificateKeyFile arg Certificate and key file for TLS --tlsCertificateKeyFilePassword arg Password to unlock key in the TLS certificate key file --tlsClusterFile arg Key file for internal TLS authentication --tlsClusterPassword arg Internal authentication key file password --tlsCAFile arg Certificate Authority file for TLS --tlsClusterCAFile arg CA used for verifying remotes during inbound connections --tlsCRLFile arg Certificate Revocation List file for TLS --tlsDisabledProtocols arg Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2] --tlsAllowConnectionsWithoutCertificates Allow client to connect without presenting a certificate --tlsAllowInvalidHostnames Allow server certificates to provide non-matching hostnames --tlsAllowInvalidCertificates Allow connections to servers with invalid certificates --tlsFIPSMode Activate FIPS 140-2 mode at startup --tlsCertificateSelector arg TLS Certificate in system store --tlsClusterCertificateSelector arg SSL/TLS Certificate in system store for internal TLS authentication --tlsLogVersions arg Comma separated list of TLS protocols to log on connect [TLS1_0,TLS1_1,TLS1_2 ] Windows Service Control Manager options: --install Install Windows service --remove Remove Windows service --reinstall Reinstall Windows service (equivalent to --remove followed by --install) --serviceName arg Windows service name --serviceDisplayName arg Windows service display name --serviceDescription arg Windows service description --serviceUser arg Account for service execution --servicePassword arg Password used to authenticate serviceUser D:\MongoDB\Server\4.2\bin>net stop MongoDB MongoDB Server (MongoDB) 服務(wù)已成功停止。 D:\MongoDB\Server\4.2\bin>net start MongoDB MongoDB Server (MongoDB) 服務(wù)正在啟動(dòng) .. MongoDB Server (MongoDB) 服務(wù)已經(jīng)啟動(dòng)成功。 D:\MongoDB\Server\4.2\bin>mongo MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("c14b3b14-14e6-4f45-85d1-0a209ac99ac0") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users > use admin switched to db admin > show users { "_id" : "admin.admin", "userId" : UUID("ee717096-e66e-4554-95a5-29aafd999c86"), "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use admin switched to db admin > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users > db.user.find() { "_id" : ObjectId("5ea2a7feaf59424af80005c6"), "id" : 1, "user_name" : "pzj", "note" : "用戶pzj", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會(huì)員" } } { "_id" : ObjectId("5ea2a87daf59424af80005c7"), "id" : 2, "user_name" : "pzj1", "note" : "用戶pzj1", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會(huì)員" } } { "_id" : ObjectId("5ea2a898af59424af80005c8"), "id" : 3, "user_name" : "pzj3", "note" : "用戶pzj3", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會(huì)員" } } { "_id" : ObjectId("5ea2a89eaf59424af80005c9"), "id" : 4, "user_name" : "pzj4", "note" : "用戶pzj4", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會(huì)員" } } > db.createUser( ... ... { ... ... user : "springboot", ... ... pwd : "123456", ... ... roles: [ { role : "readWrite", db : "springboot" }] ... ... } ... ... ) Successfully added user: { "user" : "springboot", "roles" : [ { "role" : "readWrite", "db" : "springboot" } ] } > use admin switched to db admin > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users { "_id" : "springboot.springboot", "userId" : UUID("da61542e-0c24-49b1-aa36-378580a2627a"), "user" : "springboot", "db" : "springboot", "roles" : [ { "role" : "readWrite", "db" : "springboot" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > show user 2020-04-24T21:16:27.933+0800 E QUERY [js] uncaught exception: Error: don't know how to show [user] : shellHelper.show@src/mongo/shell/utils.js:1139:11 shellHelper@src/mongo/shell/utils.js:790:15 @(shellhelp2):1:1 > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users { "_id" : "springboot.springboot", "userId" : UUID("da61542e-0c24-49b1-aa36-378580a2627a"), "user" : "springboot", "db" : "springboot", "roles" : [ { "role" : "readWrite", "db" : "springboot" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > springboot.user 2020-04-24T21:16:57.022+0800 E QUERY [js] uncaught exception: ReferenceError: springboot is not defined : @(shell):1:1 > db.user.findOne({id:1}) { "_id" : ObjectId("5ea2a7feaf59424af80005c6"), "id" : 1, "user_name" : "pzj", "note" : "用戶pzj", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會(huì)員" } } > show dbs; admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use xx switched to db xx > show dbs; admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB >
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- springboot啟動(dòng)時(shí)候報(bào)錯(cuò)mongodb問題
- Mongodb啟動(dòng)報(bào)錯(cuò)完美解決方案:about to fork child process,waiting until server is ready for connections.
- MongoDB啟動(dòng)報(bào)錯(cuò) 28663 Cannot start server
- window下mongodb在dos下服務(wù)器啟動(dòng)及連接
- Windows系統(tǒng)啟動(dòng)MongoDB報(bào)錯(cuò)無法連接服務(wù)器的問題及解決方案
相關(guān)文章
SpringBoot整合MyBatis-Plus3.1教程詳解
這篇文章主要介紹了SpringBoot整合MyBatis-Plus3.1詳細(xì)教程,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08IDEA2020.1使用LeetCode插件運(yùn)行并調(diào)試本地樣例的方法詳解
這篇文章主要介紹了IDEA2020.1使用LeetCode插件運(yùn)行并調(diào)試本地樣例的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-09-09mybatis自定義參數(shù)類型轉(zhuǎn)換器數(shù)據(jù)庫字段加密脫敏
這篇文章主要為大家介紹了mybatis自定義參數(shù)類型轉(zhuǎn)換器數(shù)據(jù)庫字段加密脫敏,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Java實(shí)現(xiàn)幀動(dòng)畫的實(shí)例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)幀動(dòng)畫的實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05SpringBoot項(xiàng)目中feignClient使用方式
文章介紹了在Spring Boot項(xiàng)目中配置Feign客戶端攔截器的具體步驟,包括在application.yml中添加配置、在主類上啟用組件掃描、將攔截器加入到攔截器列表中以及在接口調(diào)用時(shí)的說明,總結(jié)指出這是個(gè)人經(jīng)驗(yàn)分享,希望對(duì)大家有所幫助2024-11-11