Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Diese Seite enthält Codebeispiele für die Verwendung der untergeordneten Memcache API in Java. Memcache ist ein leistungsstarkes, verteiltes Speicherobjekt-Caching-System, das schnellen Zugriff auf im Cache gespeicherte Daten bietet. Weitere Informationen zu Memcache finden Sie in der Übersicht über Memcache.
Synchrone Verwendung
Beispiel für eine untergeordnete API mit dem synchronen MemcacheService:
@SuppressWarnings("serial")// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.@WebServlet(name="MemcacheSync",description="Memcache:Synchronous",urlPatterns="/memcache/sync")publicclassMemcacheSyncCacheServletextendsHttpServlet{@OverridepublicvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsIOException,ServletException{Stringpath=req.getRequestURI();if(path.startsWith("/favicon.ico")){return;// ignore the request for favicon.ico}MemcacheServicesyncCache=MemcacheServiceFactory.getMemcacheService();syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));Stringkey="count-sync";byte[]value;longcount=1;value=(byte[])syncCache.get(key);if(value==null){value=BigInteger.valueOf(count).toByteArray();syncCache.put(key,value);}else{// Increment valuecount=newBigInteger(value).longValue();count++;value=BigInteger.valueOf(count).toByteArray();// Put back in cachesyncCache.put(key,value);}// Output contentresp.setContentType("text/plain");resp.getWriter().print("Valueis " +count+"\n");}}
Asynchrone Verwendung
Beispiel für eine untergeordnete API mit AsyncMemcacheService:
AsyncMemcacheServiceasyncCache=MemcacheServiceFactory.getAsyncMemcacheService();asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));Stringkey="count-async";byte[]value;longcount=1;Future<Object>futureValue=asyncCache.get(key);// Read from cache.// ... Do other work in parallel to cache retrieval.try{value=(byte[])futureValue.get();if(value==null){value=BigInteger.valueOf(count).toByteArray();asyncCache.put(key,value);}else{// Increment valuecount=newBigInteger(value).longValue();count++;value=BigInteger.valueOf(count).toByteArray();// Put back in cacheasyncCache.put(key,value);}}catch(InterruptedException|ExecutionExceptione){thrownewServletException("Errorwhenwaitingforfuturevalue",e);}
Weitere Informationen zur untergeordneten API finden Sie im Memcache-Javadoc.