代码之家  ›  专栏  ›  技术社区  ›  mithrandir

使用凭据连接到MongoDB-Micronaut

  •  0
  • mithrandir  · 技术社区  · 6 年前

    documentation 这可以用 application.xml

    mongodb:
        uri: mongodb://username:password@localhost:27017/databaseName
    

    在我们的场景中,凭证存储在一个加密的存储区中,需要在建立到MongoDB的连接之前读取这些凭证。

    有没有一种方法可以在MongoClient实例化期间注入凭据,以便可以使用注入的凭据连接到托管MongoDB实例?

    micronaut-mongo-reactive

    0 回复  |  直到 6 年前
        1
  •  1
  •   mithrandir    6 年前

    如果这对任何人都有帮助,以下方法是有效的!!

    创建一个新工厂 @Replaces 允许重写MongoClient的默认注入的注释。在这个类中,从加密存储读取凭证,然后使用相同的凭证来构造Mongo连接字符串

    @Factory
    public class MongoClientFactory {
    
      private static final FluentLogger logger = FluentLogger.forEnclosingClass();
    
      @Inject EncryptedStoreService encryptedStoreService;
    
      @Singleton
      @Bean(preDestroy = "close")
      @Replaces(MongoClient.class)
      public MongoClient mongoClient() {
    
        MongoClient mongoClient = null;
        try {
    
        // Formulate a ConnectionString based on data read using the encryptedStoreService
    
          mongoClient = MongoClients.create(connectionString);
    
        } catch (IOException e) {
          logger.atSevere().log("Error occured", e);
        }
    
        return mongoClient;
      }
     } 
    

    爱Micronaut!!

    推荐文章