Java Spring数据MongoDB身份验证错误

Java Spring数据MongoDB身份验证错误,java,spring,mongodb,spring-mvc,spring-data-mongodb,Java,Spring,Mongodb,Spring Mvc,Spring Data Mongodb,我无法插入带有spring data mongodb的文档对象。我在spring mvc项目中配置了MongoDB,如下所示: @Configuration @EnableMongoRepositories(basePackages = { "com.example.store.repository" }) public class MongoConfiguration extends AbstractMongoConfiguration { @Bean public Mong

我无法插入带有spring data mongodb的文档对象。我在spring mvc项目中配置了MongoDB,如下所示:

@Configuration
@EnableMongoRepositories(basePackages = { "com.example.store.repository" })
public class MongoConfiguration extends AbstractMongoConfiguration {

    @Bean
    public Mongo mongo() throws UnknownHostException {
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoCredential credential = MongoCredential.createMongoCRCredential("username", "store", "password".toCharArray());
        MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(4).socketKeepAlive(true).build();
        Mongo mongo = new MongoClient(serverAddress, Arrays.asList(credential), options);
        return mongo;
    }

    @Bean(name = "MongoTemplate")
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), "store");
    }

    @Override
    protected String getDatabaseName() {
        return "store";
    }

} 
@RequestMapping(value="/add", method=RequestMethod.GET)
public String addProduct() {
    Product product = new Product();
    product.setName("New Product");
    product.setDescription("Product Description");
    product.setUnitPrice(19.99);

    productRepository.insert(product);

    return "redirect:/";
}
我还添加了存储库和文档。在我的一个控制器中,我插入一个伪文档,如下所示:

@Configuration
@EnableMongoRepositories(basePackages = { "com.example.store.repository" })
public class MongoConfiguration extends AbstractMongoConfiguration {

    @Bean
    public Mongo mongo() throws UnknownHostException {
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoCredential credential = MongoCredential.createMongoCRCredential("username", "store", "password".toCharArray());
        MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(4).socketKeepAlive(true).build();
        Mongo mongo = new MongoClient(serverAddress, Arrays.asList(credential), options);
        return mongo;
    }

    @Bean(name = "MongoTemplate")
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), "store");
    }

    @Override
    protected String getDatabaseName() {
        return "store";
    }

} 
@RequestMapping(value="/add", method=RequestMethod.GET)
public String addProduct() {
    Product product = new Product();
    product.setName("New Product");
    product.setDescription("Product Description");
    product.setUnitPrice(19.99);

    productRepository.insert(product);

    return "redirect:/";
}
当我输入此方法对应的url时,需要几秒钟的时间,并出现以下错误:

 Request processing failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }}}]

我不能透露这个问题。我在上面配置了一个用户,我能够以该用户的身份在MongoShell中执行写和读查询。然而,它在春天失败了。为什么?

您可以尝试一下这段代码,因为MongoConfiguration它可能会帮助您,并让我知道它是否解决了您的问题

@Configuration
@EnableMongoRepositories(basePackages = { "com.example.store.repository" })
public class MongoConfiguration extends AbstractMongoConfiguration {

  @Bean
  public Mongo mongo() throws UnknownHostException {
    return mongoClient();
  }

  @Bean
  public MongoDbFactory mongoDbFactory() {
    return new SimpleMongoDbFactory(mongoClient(), getDatabaseName());
  }

  @Bean
  public MongoTemplate mongoTemplate() {
    return new MongoTemplate(mongoDbFactory(), null);
  }

  @Override
  protected String getDatabaseName() {
    return "store";
  }

  @Bean
  public MongoClient mongoClient() {    
    List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
    credentialsList.add(MongoCredential.createCredential("username", getDatabaseName(), "password".toCharArray());
    ServerAddress primary = new ServerAddress("localhost", 27017);
    MongoClientOptions mongoClientOptions = MongoClientOptions.builder().connectionsPerHost(4).socketKeepAlive(true).build();
    return new MongoClient(Arrays.aslist(primary), credentialsList, mongoClientOptions); 
  }

}
@配置
@EnableMongorPositories(basePackages={“com.example.store.repository”})
公共类MongoConfiguration扩展了AbstractMongoConfiguration{
@豆子
public Mongo Mongo()抛出UnknownHostException{
返回mongoClient();
}
@豆子
公共MongoDbFactory MongoDbFactory(){
返回新的SimpleMongoDbFactory(mongoClient(),getDatabaseName());
}
@豆子
公共MongoTemplate MongoTemplate(){
返回新的MongoTemplate(mongoDbFactory(),null);
}
@凌驾
受保护的字符串getDatabaseName(){
返回“存储”;
}
@豆子
公共MongoClient MongoClient(){
List-credentialsList=new-ArrayList();
credentialsList.add(MongoCredential.createCredential(“username”,getDatabaseName(),“password.toCharray());
ServerAddress primary=新服务器地址(“本地主机”,27017);
MongoClientOptions MongoClientOptions=MongoClientOptions.builder().connectionsPerHost(4.socketKeepAlive(true.build));
返回新的MongoClient(Arrays.aslist(primary)、credentialsList、MongoClient);
}
}

上面的配置在您的上下文中创建了多个类型为
MongoTemplate
的bean。声明为
@bean(name=“MongoTemplate”)的bean
将不会在存储库中使用。虽然这不会导致您遇到的错误…因此,请尝试删除手动声明的bean,除非它与代码中的某个
@限定符一起使用,然后再试一次。您有没有复制错误的小样本可以告诉我?哪个MongoDB服务器,m您使用的是ongo java client和Spring Data MongoDB版本吗?@ChristophStrobl事实上,先生,我不清楚到底发生了什么。我试图通过使用本文来实现它:。我让mongodb3在同一台机器上运行。mongo java驱动程序:3.1.0。