我想使用Restlet处理对某些信息的请求,但是此信息需要花费一些时间从磁盘加载,因此我想在启动Restlet服务器时而不是在我的Resource类中执行此步骤,该类似乎已实例化。每个请求。换句话说,我想一次将其加载到内存中。

我正在看本教程:http://www.2048bits.com/2008/06/creating-simple-web-service-with.html,并假设每次有人请求/ Users时,router.attach("/users", UserResource.class);实例化一个新的UserResource()对象。假设我想将User数据库加载到内存中,以便在UserResource.findUser()中进行快速查找。

更新:也许这样的答案可以帮助我吗? https://stackoverflow.com/a/7865506/318870

更新2:我认为我找到了解决方案,因此请尽快将我的发现回发

最佳答案

在Restlet书和their public source code中,他们仅使用getApplication()类中的Resource函数:

public class Application extends org.restlet.Application {

    public static void main(String... args) throws Exception {
        // Create a component with an HTTP server connector
        final Component comp = new Component();
        comp.getServers().add(Protocol.HTTP, 3000);

        // Attach the application to the default host and start it
        comp.getDefaultHost().attach("/v1", new Application());
        comp.start();
    }

    private final ObjectContainer container;

    /**
     * Constructor.
     */
    public Application() {
        /** Open and keep the db4o object container. */
        EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
        config.common().updateDepth(2);
        this.container = Db4oEmbedded.openFile(config, System
                .getProperty("user.home")
                + File.separator + "restbook.dbo");
    }

    @Override
    public Restlet createInboundRoot() {
        final Router router = new Router(getContext());

        // Add a route for user resources
        router.attach("/users/{username}", UserResource.class);

        // Add a route for user's bookmarks resources
        router.attach("/users/{username}/bookmarks", BookmarksResource.class);

        // Add a route for bookmark resources
        final TemplateRoute uriRoute = router.attach(
                "/users/{username}/bookmarks/{URI}", BookmarkResource.class);
        uriRoute.getTemplate().getVariables().put("URI",
                new Variable(Variable.TYPE_URI_ALL));

        return router;
    }

    /**
     * Returns the database container.
     *
     * @return the database container.
     */
    public ObjectContainer getContainer() {
        return this.container;
    }
}


/** resource class (UserResource.java) has these functions
/**
 * Returns the parent application.
 *
 * @return the parent application.
 */
@Override
public Application getApplication() {
    return (Application) super.getApplication();
}

/**
 * Returns the database container.
 *
 * @return the database container.
 */
public ObjectContainer getContainer() {
    return getApplication().getContainer();
}

关于java - 使用ReSTLet,在哪里可以预加载某些内容,以便每次访问资源时都不会对其进行处理?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8316961/

10-12 23:01