我需要浏览JackRabbit存储库。我正在使用以下代码进行连接:

Repository repository = JcrUtils.getRepository(url);
SimpleCredentials credentials = new SimpleCredentials(user, password.toCharArray());
session = repository.login(credentials, workspace);


但是,如果由于某种原因某些参数不正确,我的Web应用程序将被卡住。我需要做的是设置一个超时连接(例如30秒),但是在jcr API中找不到任何方法。
关于如何执行此操作的任何建议或代码示例?

PS:我使用的jackrabbit版本是2.2.10。

最佳答案

因此,我设法使用FutureTask添加连接超时。
我创建了一个实现Callable接口的类,并在call()方法中放入了连接逻辑:

public class CallableSession implements Callable<Session> {

private final String url;
private final String user;
private final String password;
private final String workspace;

public CallableSession(String url, String user, String password, String workspace) {
    this.url = url;
    this.user = user;
    this.password = password;
    this.workspace = workspace;
}

@Override
public Session call() throws Exception {

    Repository repository = JcrUtils.getRepository(url);
    SimpleCredentials credentials = new SimpleCredentials(user, password.toCharArray());
    Session session = repository.login(credentials, workspace);

    return session;
}


接下来,在getSession()函数内的连接器类中,创建一个FutureTask,执行它并放置连接超时:

public Session getSession() {

    if (session == null) {
        try {
            CallableSession cs = new CallableSession(url, user, password, workspace);
            FutureTask<Session> future = new FutureTask<Session>(cs);
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.execute(future);
            session = future.get(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);

        } catch (InterruptedException ex) {
            Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TimeoutException ex) {
            Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return session;
}

10-07 19:52
查看更多