且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正确设置简单的服务器端缓存

更新时间:2023-11-27 22:34:52

您正在这样做.单调风味的图案是完全没有必要的.只需实现 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();
// ...