且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 ssl 从 Spring Boot 应用程序连接到 MongoDB

更新时间:2023-01-20 08:09:07

我建议你看一下 Accessing Data with MongoDB 可用这里 https://spring.io/guides/gs/accessing-data-mongodb/ 基本用法示例.spring-boot-starter-data-mongodb 会让你走得很远,你需要做的是像这样配置一个 MongoClientOptions bean

I would suggest that you look at Accessing Data with MongoDB available here https://spring.io/guides/gs/accessing-data-mongodb/ for basic usage examples. spring-boot-starter-data-mongodb will get you a long way, what you need to do is configure a MongoClientOptions bean like this

    @Bean
    public  MongoClientOptions mongoClientOptions(){
        System.setProperty ("javax.net.ssl.keyStore","<<PATH TO KEYSTOR >>");
        System.setProperty ("javax.net.ssl.keyStorePassword","PASSWORD");   
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        MongoClientOptions options=builder.sslEnabled(true).build();        
        return options;
    }

并将 mongo 客户端选项作为参数传递给 MongoClient 实例,如下所示

and pass the mongo client options to MongoClient instance as an argument as follows

public MongoClient(ServerAddress addr, MongoClientOptions options) {
        super(addr, options);
    }

进一步添加,当 mongo 进程启动时

Adding further, when mongo processs is started with

mongo --ssl --sslAllowInvalidCertificates --host --port

mongo --ssl --sslAllowInvalidCertificates --host --port

连接到 mongo 进程的客户端不必设置任何选项来支持这一点.

clients connecting to the mongo process dont have to set any options to support this.

我用过这个帖子Spring数据mongodb,如何设置SSL? 和这个 spring.io 指南作为参考.

I used this post Spring data mongodb, how to set SSL? and this spring.io guide as reference.

希望对你有帮助