简体   繁体   中英

Anyway to open/close memcached server in java application?

So I've got a little REST API I've developed that incorporates a cache to cache data from a database for efficiency purposes. As it now stands, I have to start up the server separately from command line, and then run my web application. When I terminate my web application I then have to go back to command line and close the server there as well. Is there anyway to start the memcached server automatically (like with code) when I start my java application and/or close it when I terminate it?

If you prefer doing it from java code, you could use a ProcessBuilder to invoke the memcache startup/shutdown script(code example from javadoc):

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();

And you need to implement a ServletContextListener to receive servlet context lifecycle events, ie initialize & destroy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM