正确设置简单的服务器端缓存 [英] Properly setting up a simple server-side cache
问题描述
我正在尝试正确设置服务器端缓存,并且正在寻找对当前设置的建设性批评. Servlet启动时将加载缓存,并且再也不会更改,因此实际上是只读缓存.很显然,它需要在Servlet的生命周期内保留在内存中.这是我的设置方式
I'm trying to set up a server-side cache properly and I'm looking for constructive criticism on the setup I have currently. The cache is loaded when the Servlet starts and never changed again, so in effect it's a read-only cache. It obviously needs to stay in memory for the lifetime of the Servlet. Here's how I have it set-up
private static List<ProductData> _cache;
private static ProductManager productManager;
private ProductManager() {
try {
lookup();
} catch (Exception ex) {
_cache = null;
}
}
public synchronized static ProductManager getInstance() {
if (productManager== null) {
productManager= new ProductManager();
}
return productManager;
}
高速缓存是由Servlet设置的,如下所示:
The cache is setup by the Servlet as below:
private ProductManager productManager;
public void init(ServletConfig config) throws ServletException {
productManager = ProductManager.getInstance();
}
最后,这就是我的访问方式:
And finally, this is how I access it:
public static ProductData lookup(long id) throws Exception {
if (_cache != null) {
for (int i = 0; i < _cache.size(); i++) {
if (_cache.get(i).id == id) {
return _cache.get(i);
}
}
}
// Look it up in the DB.
}
public static List<ProductData> lookup() throws Exception {
if (_cache != null) {
return _cache;
}
// Read it from the DB.
_cache = list;
return list;
}
推荐答案
您正在这样做.单调风味的图案是完全没有必要的.只需实现 ServletContextListener
即可在网络应用启动(和关闭)时进行,这样您就可以在网络应用启动期间将数据加载并存储在应用范围中.
You're doing it the hard way. A singleton-flavored pattern is completely unnecessary. Just implement a ServletContextListener
to have a hook on the webapp startup (and shutdown), so that you can just load and store the data in the application scope during the webapp startup.
public class Config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "com.example.Config";
private Map<Long, Product> products;
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
context.setAttribute(ATTRIBUTE_NAME, this);
String dbname = context.getInitParameter("dbname");
products = Database.getInstance(dbname).getProductDAO().map();
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
public static Config getInstance(ServletContext context) {
return (Config) context.getAttribute(ATTRIBUTE_NAME);
}
public Map<Long, Product> getProducts() {
return products;
}
}
您要在web.xml
中进行以下注册:
Which you register in web.xml
as follows:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
这样,您可以在任何servlet中获取它,如下所示:
This way you can get it in any servlet as follows:
Config config = Config.getInstance(getServletContext());
Map<Long, Product> products = config.getProducts();
// ...
这篇关于正确设置简单的服务器端缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!