View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.impl.cache.memcached;
28  
29  import java.io.IOException;
30  import java.net.InetSocketAddress;
31  import java.util.Collection;
32  import java.util.HashMap;
33  import java.util.Map;
34  
35  import org.apache.hc.client5.http.cache.HttpCacheEntrySerializer;
36  import org.apache.hc.client5.http.cache.ResourceIOException;
37  import org.apache.hc.client5.http.impl.cache.AbstractBinaryCacheStorage;
38  import org.apache.hc.client5.http.impl.cache.ByteArrayCacheEntrySerializer;
39  import org.apache.hc.client5.http.impl.cache.CacheConfig;
40  import org.apache.hc.core5.util.Args;
41  
42  import net.spy.memcached.CASResponse;
43  import net.spy.memcached.CASValue;
44  import net.spy.memcached.MemcachedClient;
45  import net.spy.memcached.OperationTimeoutException;
46  
47  /**
48   * <p>
49   * This class is a storage backend that uses an external <i>memcached</i>
50   * for storing cached origin responses. This storage option provides a
51   * couple of interesting advantages over the default in-memory storage
52   * backend:
53   * </p>
54   * <ol>
55   * <li>in-memory cached objects can survive an application restart since
56   * they are held in a separate process</li>
57   * <li>it becomes possible for several cooperating applications to share
58   * a large <i>memcached</i> farm together</li>
59   * </ol>
60   * <p>
61   * Note that in a shared memcached pool setting you may wish to make use
62   * of the Ketama consistent hashing algorithm to reduce the number of
63   * cache misses that might result if one of the memcached cluster members
64   * fails (see the <a href="http://dustin.github.com/java-memcached-client/apidocs/net/spy/memcached/KetamaConnectionFactory.html">
65   * KetamaConnectionFactory</a>).
66   * </p>
67   * <p>
68   * Because memcached places limits on the size of its keys, we need to
69   * introduce a key hashing scheme to map the annotated URLs the higher-level
70   * caching HTTP client wants to use as keys onto ones that are suitable
71   * for use with memcached. Please see {@link KeyHashingScheme} if you would
72   * like to use something other than the provided {@link SHA256KeyHashingScheme}.
73   * </p>
74   *
75   * <p>
76   * Please refer to the <a href="http://code.google.com/p/memcached/wiki/NewStart">
77   * memcached documentation</a> and in particular to the documentation for
78   * the <a href="http://code.google.com/p/spymemcached/">spymemcached
79   * documentation</a> for details about how to set up and configure memcached
80   * and the Java client used here, respectively.
81   * </p>
82   *
83   * @since 4.1
84   */
85  public class MemcachedHttpCacheStorage extends AbstractBinaryCacheStorage<CASValue<Object>> {
86  
87      private final MemcachedClient client;
88      private final KeyHashingScheme keyHashingScheme;
89  
90      /**
91       * Create a storage backend talking to a <i>memcached</i> instance
92       * listening on the specified host and port. This is useful if you
93       * just have a single local memcached instance running on the same
94       * machine as your application, for example.
95       * @param address where the <i>memcached</i> daemon is running
96       * @throws IOException in case of an error
97       */
98      public MemcachedHttpCacheStorage(final InetSocketAddress address) throws IOException {
99          this(new MemcachedClient(address));
100     }
101 
102     /**
103      * Create a storage backend using the pre-configured given
104      * <i>memcached</i> client.
105      * @param cache client to use for communicating with <i>memcached</i>
106      */
107     public MemcachedHttpCacheStorage(final MemcachedClient cache) {
108         this(cache, CacheConfig.DEFAULT, ByteArrayCacheEntrySerializer.INSTANCE, SHA256KeyHashingScheme.INSTANCE);
109     }
110 
111     /**
112      * Create a storage backend using the given <i>memcached</i> client and
113      * applying the given cache configuration, serialization, and hashing
114      * mechanisms.
115      * @param client how to talk to <i>memcached</i>
116      * @param config apply HTTP cache-related options
117      * @param serializer alternative serialization mechanism
118      * @param keyHashingScheme how to map higher-level logical "storage keys"
119      *   onto "cache keys" suitable for use with memcached
120      */
121     public MemcachedHttpCacheStorage(
122             final MemcachedClient client,
123             final CacheConfig config,
124             final HttpCacheEntrySerializer<byte[]> serializer,
125             final KeyHashingScheme keyHashingScheme) {
126         super((config != null ? config : CacheConfig.DEFAULT).getMaxUpdateRetries(),
127                 serializer != null ? serializer : ByteArrayCacheEntrySerializer.INSTANCE);
128         this.client = Args.notNull(client, "Memcached client");
129         this.keyHashingScheme = keyHashingScheme;
130     }
131 
132     @Override
133     protected String digestToStorageKey(final String key) {
134         return keyHashingScheme.hash(key);
135     }
136 
137     @Override
138     protected void store(final String storageKey, final byte[] storageObject) throws ResourceIOException {
139         client.set(storageKey, 0, storageObject);
140     }
141 
142     private byte[] castAsByteArray(final Object storageObject) throws ResourceIOException {
143         if (storageObject == null) {
144             return null;
145         }
146         if (storageObject instanceof byte[]) {
147             return (byte[]) storageObject;
148         }
149         throw new ResourceIOException("Unexpected cache content: " + storageObject.getClass());
150     }
151 
152     @Override
153     protected byte[] restore(final String storageKey) throws ResourceIOException {
154         try {
155             return castAsByteArray(client.get(storageKey));
156         } catch (final OperationTimeoutException ex) {
157             throw new MemcachedOperationTimeoutException(ex);
158         }
159     }
160 
161     @Override
162     protected CASValue<Object> getForUpdateCAS(final String storageKey) throws ResourceIOException {
163         try {
164             return client.gets(storageKey);
165         } catch (final OperationTimeoutException ex) {
166             throw new MemcachedOperationTimeoutException(ex);
167         }
168     }
169 
170     @Override
171     protected byte[] getStorageObject(final CASValue<Object> casValue) throws ResourceIOException {
172         return castAsByteArray(casValue.getValue());
173     }
174 
175     @Override
176     protected boolean updateCAS(
177             final String storageKey, final CASValue<Object> casValue, final byte[] storageObject) throws ResourceIOException {
178         final CASResponse casResult = client.cas(storageKey, casValue.getCas(), storageObject);
179         return casResult == CASResponse.OK;
180     }
181 
182     @Override
183     protected void delete(final String storageKey) throws ResourceIOException {
184         client.delete(storageKey);
185     }
186 
187     @Override
188     protected Map<String, byte[]> bulkRestore(final Collection<String> storageKeys) throws ResourceIOException {
189         final Map<String, ?> storageObjectMap = client.getBulk(storageKeys);
190         final Map<String, byte[]> resultMap = new HashMap<>(storageObjectMap.size());
191         for (final Map.Entry<String, ?> resultEntry: storageObjectMap.entrySet()) {
192             resultMap.put(resultEntry.getKey(), castAsByteArray(resultEntry.getValue()));
193         }
194         return resultMap;
195     }
196 
197 }