java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot启动mongoDB报错禁用mongoDB自动配置

springboot启动mongoDB报错之禁用mongoDB自动配置问题

作者:lv_hang515888

这篇文章主要介绍了springboot启动mongoDB报错之禁用mongoDB自动配置问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

springboot启动mongoDB报错之禁用mongoDB自动配置

错误信息如下:

springboot自动配置了支持mongodb。

在启动springboot时会自动实例化一个mongo实例。

所以自己配置的话,需要禁用掉springboot的自动配置。

@SpringBootApplication(exclude = {MongoAutoConfiguration.class,MongoDataAutoConfiguration.class})

这个注解可以禁用springboot自带的配置。

如下图:

springboot整合MongoDB时碰到的问题

1.账号总是不对,导致查不出数据,报错Auth…权鉴错误

这次,我也是第一次接触MongoDB,非常的生疏

springboot整合MongoDB,要在properties文件中配置账号

mongodb基本语法:

use DATABASE_NAME; --创建数据库
show dbs;   --查看我们所有的库,注意,我们刚创建的库,如果没有数据,是不会被显示的
show users;  --查看当前库所有拥有的账号
db.createCollection(name, options) --在当前数据库中创建集合
show tables  --查看当前库中有哪些集合

--在当前数据库中创建用户并设置密码及权限
db.createUser(
... {
...  user : "aaa",
...  pwd : "123456",
...  roles: [ { role : "readWrite", db : "springboot" }]
... }
... )

通过上面的基础铺垫:

1.首先我们要登录MongoDB数据库

用管理员权限运行cmd

进入我们安装的MongoDB的bin目录下执行命令

mongo

即可登录MongoDB数据库

2.创建数据库

use springboot;

3.创建数据库对应的账号

创建一个springboot账号,对springboot数据库拥有读写权限

db.createUser(
... {
...  user : "springboot",
...  pwd : "123456",
...  roles: [ { role : "readWrite", db : "springboot" }]
... }
... )

4.在springboot库中创建集合user

db.createCollection("user");   --创建集合user
show tables;        --查看当前库中所有的集合
--- 并给集合user添加一条数据
db.user.insert({
        "user_name":"pzj",
        "note":"用户pzj",
        "roles":[{
            "role_name": "vip_user",
            "note": "会员"
        }]
})

到此,MongoDB的数据库初始化完成。

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.查询时遇见的错误

No converter found capable of converting from org.bson.types.ObjectId to type Long异常

这个问题很好解决

我们在创建实体类对应数据库中的集合user时,把id设置成了Long型,导致的报错

我们只要把id类型改成String即可。

在MongoDb里要求每个文档都需要有_id 字段,java类中有如下情况会被映射为_id字段

如果1个字段加上了 @Id (org.springframework.data.annotation.Id)注解,那么将bean保存到数据库时就会把该字段映射为文档中的_id字段

如果java对象中没有 @Id 注解,名字为id 的字段将会被映射为文档中的_id字段

所以,也可以看出,我们的MongoDB数据,是不需要我们人为的添加主键id字段的

这个和以往的mysq等关系型数据库有所不同

它会自动给我们生成一个_id字段,作为集合的主键,标识一条数据

我的操作记录:

Microsoft Windows [版本 10.0.17134.81]
(c) 2018 Microsoft Corporation。保留所有权利。

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' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

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) 服务已成功停止。


D:\MongoDB\Server\4.2\bin>net start MongoDB
MongoDB Server (MongoDB) 服务正在启动 ..
MongoDB Server (MongoDB) 服务已经启动成功。


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" : "会员" } }
{ "_id" : ObjectId("5ea2a87daf59424af80005c7"), "id" : 2, "user_name" : "pzj1", "note" : "用户pzj1", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "会员" } }
{ "_id" : ObjectId("5ea2a898af59424af80005c8"), "id" : 3, "user_name" : "pzj3", "note" : "用户pzj3", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "会员" } }
{ "_id" : ObjectId("5ea2a89eaf59424af80005c9"), "id" : 4, "user_name" : "pzj4", "note" : "用户pzj4", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "会员" } }
> 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" : "会员"
        }
}
> 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
>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文