MongoDB如果使用uri来连接数据库,会出现特殊密码字符的问题,尤其是在docker容器等第三方部署工具中,会使用环境变量设置密码,而密码又没有明确转义的时候,会导致无法正常启动应用程序和连接MongoDB数据库。
MongoDB数据库对以下特殊字符需要转义: []/?#@
- import com.mongodb.ConnectionString;
- import com.mongodb.client.MongoClient;
- import com.mongodb.client.MongoClients;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- * MongoDB connection configuration
- * <p>
- * In docker pods, using ENV variable to set the password and the password contains special chars<br/>
- * To support special chars in password, we had to escape password first
- */
- @Configuration
- public class MongoConfiguration {
- @Value("${spring.data.mongodb.username}")
- private String user;
- @Value("${spring.data.mongodb.password}")
- private String password;
- @Value("${spring.data.mongodb.hosts}")
- private String hosts;
- @Value("${spring.data.mongodb.database}")
- private String database;
- @Value("${spring.data.mongodb.options:authSource=admin&tls=true&maxPoolSize=10&minPoolSize=2&connectTimeoutMS=60000&socketTimeoutMS=60000}")
- private String options;
- @Bean
- MongoClient mongoClient() {
- String uri = String.format("mongodb://%s:%s@%s/%s?%s", user, escape(password), hosts, database, options);
- ConnectionString connectionString = new ConnectionString(uri);
- return MongoClients.create(connectionString);
- }
-
- * Escape special char of password for MongoDB connection string
- *
- * @param password Raw password string, might from ENV variable
- * @return escaped password
- */
- private String escape(String password) {
- return password.replace("@", "%40")
- .replace("/", "%2F")
- .replace("?", "%3F")
- .replace("[", "%5B")
- .replace("]", "%5D")
- .replace(",", "%2C")
- .replace("#", "%23");
- }
- }
application.properties中,需要添加配置:
- spring.data.mongodb.username=username
- spring.data.mongodb.password=password
- spring.data.mongodb.hosts=s1.abc.com:123,s2.abc.com:123,www.abc.com:456
- spring.data.mongodb.database=demo
- spring.data.mongodb.options=authSource=admin&tls=true&maxPoolSize=10&minPoolSize=2&connectTimeoutMS=60000&socketTimeoutMS=60000&cafile=abc.pem&tls=true