Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update memcache sample with code from docs pages #176

Merged
merged 1 commit into from
Apr 21, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.memcache;

import com.google.appengine.api.memcache.AsyncMemcacheService;
import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

import java.io.IOException;
import java.math.BigInteger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class MemcacheAsyncCacheServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
return; // ignore the request for favicon.ico
}

// [START example]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The region tag name example is OK, but I'd prefer more explicit one

AsyncMemcacheService asyncCache = MemcacheServiceFactory.getAsyncMemcacheService();
asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
String key = "count-async";
byte[] value;
long count = 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 value
count = new BigInteger(value).longValue();
count++;
value = BigInteger.valueOf(count).toByteArray();
// Put back in cache
asyncCache.put(key, value);
}
} catch (InterruptedException | ExecutionException e) {
throw new ServletException("Error when waiting for future value", e);
}
// [END example]

// Output content
resp.setContentType("text/plain");
resp.getWriter().print("Value is " + count + "\n");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

// [START example]
@SuppressWarnings("serial")
public class MemcacheServlet extends HttpServlet {
public class MemcacheBestPracticeServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.memcache;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheService.IdentifiableValue;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

import java.io.IOException;
import java.math.BigInteger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// [START example]
@SuppressWarnings("serial")
public class MemcacheConcurrentServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
return; // ignore the request for favicon.ico
}

String key = "count-concurrent";
// Using the synchronous cache.
MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();

// Write this value to cache using getIdentifiable and putIfUntouched.
for (long delayMs = 1; delayMs < 1000; delayMs *= 2) {
IdentifiableValue oldValue = syncCache.getIdentifiable(key);
byte[] newValue = oldValue == null
? BigInteger.valueOf(0).toByteArray()
: increment((byte[]) oldValue.getValue()); // newValue depends on old value
resp.setContentType("text/plain");
resp.getWriter().print("Value is " + new BigInteger(newValue).intValue() + "\n");
if (oldValue == null) {
// Key doesn't exist. We can safely put it in cache.
syncCache.put(key, newValue);
break;
} else if (syncCache.putIfUntouched(key, oldValue, newValue)) {
// newValue has been successfully put into cache.
break;
} else {
// Some other client changed the value since oldValue was retrieved.
// Wait a while before trying again, waiting longer on successive loops.
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
throw new ServletException("Error when sleeping", e);
}
}
}
}

/**
* Increments an integer stored as a byte array by one.
* @param oldValue a byte array with the old value
* @return a byte array as the old value increased by one
*/
private byte[] increment(byte[] oldValue) {
long val = new BigInteger(oldValue).intValue();
val++;
return BigInteger.valueOf(val).toByteArray();
}
}
// [END example]
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.memcache;

import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

import java.io.IOException;
import java.math.BigInteger;
import java.util.logging.Level;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// [START example]
@SuppressWarnings("serial")
public class MemcacheSyncCacheServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
return; // ignore the request for favicon.ico
}

MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
String key = "count-sync";
byte[] value;
long count = 1;
value = (byte[]) syncCache.get(key);
if (value == null) {
value = BigInteger.valueOf(count).toByteArray();
syncCache.put(key, value);
} else {
// Increment value
count = new BigInteger(value).longValue();
count++;
value = BigInteger.valueOf(count).toByteArray();
// Put back in cache
syncCache.put(key, value);
}

// Output content
resp.setContentType("text/plain");
resp.getWriter().print("Value is " + count + "\n");
}
}
// [END example]
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- [START_EXCLUDE] -->
<!--
Copyright 2015 Google Inc. All Rights Reserved.
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand Down
32 changes: 28 additions & 4 deletions appengine/memcache/src/main/webapp/WEB-INF/web.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- [START_EXCLUDE] -->
<!--
Copyright 2015 Google Inc. All Rights Reserved.
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand All @@ -18,12 +18,36 @@
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>memcache</servlet-name>
<servlet-class>com.example.appengine.memcache.MemcacheServlet</servlet-class>
<servlet-name>memcache-best-practice</servlet-name>
<servlet-class>com.example.appengine.memcache.MemcacheBestPracticeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>memcache</servlet-name>
<servlet-name>memcache-best-practice</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>memcache-async</servlet-name>
<servlet-class>com.example.appengine.memcache.MemcacheAsyncCacheServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>memcache-async</servlet-name>
<url-pattern>/async</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>memcache-sync</servlet-name>
<servlet-class>com.example.appengine.memcache.MemcacheSyncCacheServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>memcache-sync</servlet-name>
<url-pattern>/sync</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>memcache-concurrent</servlet-name>
<servlet-class>com.example.appengine.memcache.MemcacheConcurrentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>memcache-concurrent</servlet-name>
<url-pattern>/concurrent</url-pattern>
</servlet-mapping>
</web-app>