我想使用Restlet处理某些信息的请求,但是这些信息需要一些时间才能从磁盘加载,所以我想在启动Restlet服务器时执行此步骤,而不是在我的Resource类中执行此步骤,在每个请求上实例化。换句话说,我想将它加载到内存中一次。
我正在查看本教程:http://www.2048bits.com/2008/06/creating-simple-web-service-with.html并假设每次有人请求/用户时,router.attach("/users", UserResource.class);
都会实例化一个新的UserResource()
对象。假设我想将用户数据库加载到内存中,以便UserResource.findUser()
中的查找速度很快。
更新:也许像这样的回答可以帮到我吗? https://stackoverflow.com/a/7865506/318870
更新2:我认为我找到了一个解决方案,所以很快就会发布我的调查结果
答案 0 :(得分:1)
从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();
}