MongoLab身份验证失败

时间:2016-02-18 04:58:35

标签: java spring-mvc heroku mlab

我已将我的Web应用程序上传到Heroku,我有一个名为“MongoLab”的插件。我将MongoLab的凭据放入我的Spring XML文件中,当我运行它时,我收到一个错误:

{"message":"Failed to authenticate to database [heroku_c82w85xw], username = [heroku_c82w85xw], password = [k************************c]","code":"org.springframework.data.mongodb.CannotGetMongoDbConnectionException

所以我还制作了一个包含凭据的Java配置文件,但我仍然得到同样的错误。我已经尝试了几个星期,但我仍然得到同样的错误。以下是我的Spring XML和Java配置文件。

Spring XML文件:

    <mongo:mongo id="mongo" host="ds055575.mongolab.com" port="55575"/>

<mongo:db-factory 
    id="mongoDbFactory"
    host="ds055575.mongolab.com"
    port="55575"
    username="heroku_c82w85xw"
    password="XXX"
    dbname="heroku_c82w85xw"
    mongo-ref="mongo"/>

<bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />  
</bean>

<bean id="userDaoImpl" class="service.UserDaoImpl">
    <constructor-arg name="mongoOps" ref="anotherMongoTemplate" />
</bean>
<bean id="userService" class="service.UserService">
    <property name="userDaoImpl" ref="userDaoImpl" />
</bean>

Java配置文件:

@Configuration
public class JavaConfig {
    public MongoClient getDB() {
        String uri = "mongodb://heroku_c82w85xw:XXX"
                + "@ds055575.mongolab.com:55575/heroku_c82w85xw?authMechanism=SCRAM-SHA-1";
        MongoClientURI mongoURI = new MongoClientURI(uri);
        MongoClient client = null;
        try {
            client = new MongoClient(mongoURI);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
}

有人可以帮我解决这个错误吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您应该从MongoLab为您设置的环境变量中提取URI,而不是对URI进行硬编码。这是一个例子:

String uri = System.getenv("MONGOLAB_URI");
MongoClientURI uri  = new MongoClientURI(uri); 
MongoClient client = new MongoClient(uri);
DB db = client.getDB(uri.getDatabase());

这就是MongoLab推荐的documentation