Search code examples
mongodbspring-bootreactive-streams

How to enable ssl in reactive mongodb client in spring boot?


I am currently running into an issue while creating a reactive mongoclient when I provide the URL with ssl=true option. I am creating configuration class in spring boot where I create Reactive mongoclient using the following option: MongoClients.create(Connections ring Conn) Here when I try to connect to a DB with no ssl settings it works, but with ssl enabled option I am getting error saying NettyEventLoop class is not found. Can anyone suggest what I can do to fix this issue


Solution

  • It seems that the API has changed, so since MongoDB driver v3.8, the method is "applyToSslSettings":

    import com.mongodb.Block;
    import com.mongodb.connection.SslSettings;
    import com.mongodb.connection.SslSettings.Builder;
    import com.mongodb.connection.netty.NettyStreamFactoryFactory;
    
    import io.netty.channel.nio.NioEventLoopGroup;
    
    @Configuration
    public class Config {
    
        private NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    
        @Bean
        public MongoClientSettingsBuilderCustomizer sslCustomizer() {
    
            Block<SslSettings.Builder> sslSettingsBlock = new Block<SslSettings.Builder>() {
                @Override
                public void apply(Builder t) {
                    t.applySettings(SslSettings.builder()
                    .enabled(true)
                    .invalidHostNameAllowed(true)
                    .build());
                }
            };
    
            return clientSettingsBuilder -> clientSettingsBuilder
                    .applyToSslSettings(sslSettingsBlock)
                    .streamFactoryFactory(NettyStreamFactoryFactory.builder()
                            .eventLoopGroup(eventLoopGroup).build());
        }
    
        @PreDestroy
        public void shutDownEventLoopGroup() {
            eventLoopGroup.shutdownGracefully();
        }
    }