net.spy.memcached.transcoders.Transcoder Java Examples

The following examples show how to use net.spy.memcached.transcoders.Transcoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExceptionSwallowingMemcachedClient.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
/**
 * Method to allow CAS 
 * @param <T>
 * @param key
 * @param mutation
 * @param value
 * @return
 */
public <T> T cas(String key,CASMutation<T> mutation,T value,int expireSecs)
{
	Transcoder transcoder = new SerializingTranscoder();
	// The mutator who'll do all the low-level stuff.
	// Set number of retries to limit time taken..its not essential this succeeds
	CASMutator<T> mutator = new CASMutator<>(memcachedClient, transcoder,MAX_CAS_RETRIES);

	// This returns whatever value was successfully stored within the
	// cache -- either the initial list as above, or a mutated existing
	// one
	try 
	{
		return mutator.cas(hashKey(key), value, expireSecs, mutation);
	} 
	catch (Exception e) 
	{
		logger.error("Failed up update hits in cache ",e);
		return null;
	}
}
 
Example #2
Source File: SpyMemcachedAdapterTest.java    From hibernate4-memcached with Apache License 2.0 6 votes vote down vote up
@Test
public void createConnectionFactoryBuilder() throws Exception {
    Properties props = new Properties();
    props.setProperty(HASH_ALGORITHM_PROPERTY_KEY, DefaultHashAlgorithm.NATIVE_HASH.name());
    props.setProperty(OPERATION_TIMEOUT_MILLIS_PROPERTY_KEY, String.valueOf(13579));
    props.setProperty(TRANSCODER_PROPERTY_KEY, FakeTranscoder.class.getName());
    props.setProperty(AUTH_GENERATOR_PROPERTY_KEY, FakeAuthDescriptorGenerator.class.getName());

    ConnectionFactoryBuilder builder = spyMemcachedAdapter.createConnectionFactoryBuilder(new OverridableReadOnlyPropertiesImpl(props));

    ConnectionFactory connectionFactory = builder.build();
    assertThat(connectionFactory.getHashAlg()).isEqualTo(DefaultHashAlgorithm.NATIVE_HASH);
    assertThat(connectionFactory.getOperationTimeout()).isEqualTo(13579);

    Transcoder<Object> transcoder = connectionFactory.getDefaultTranscoder();
    assertThat(transcoder).isExactlyInstanceOf(FakeTranscoder.class);
    FakeTranscoder fakeTranscoder = (FakeTranscoder) transcoder;
    assertThat(fakeTranscoder.isInitialized()).isTrue();

    AuthDescriptor authDescriptor = connectionFactory.getAuthDescriptor();
    assertThat(authDescriptor.getMechs()).isEqualTo(FakeAuthDescriptorGenerator.FAKE_MECHS);
}
 
Example #3
Source File: EVCacheClient.java    From EVCache with Apache License 2.0 6 votes vote down vote up
public <T> T get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF, boolean chunked) throws Exception {
    if (chunked) {
        return assembleChunks(key, false, 0, tc, hasZF);
    } else if(shouldHashKey()) {
        final String hKey = getHashedKey(key);
        final Object obj = evcacheMemcachedClient.asyncGet(hKey, evcacheValueTranscoder, null).get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF);
        if(obj instanceof EVCacheValue) {
            final EVCacheValue val = (EVCacheValue)obj;
            if(val == null || !(val.getKey().equals(key))) {
                incrementFailure(EVCacheMetricsFactory.KEY_HASH_COLLISION, Call.GET);
                return null;
            }
            final CachedData cd = new CachedData(val.getFlags(), val.getValue(), CachedData.MAX_SIZE);
            if(tc == null) {
                return (T)evcacheMemcachedClient.getTranscoder().decode(cd);
            } else {
                return tc.decode(cd);
            }
        } else {
            return null;
        }
    } else {
        return evcacheMemcachedClient.asyncGet(key, tc, null).get(readTimeout.get(),
                TimeUnit.MILLISECONDS, _throwException, hasZF);
    }
}
 
Example #4
Source File: EVCacheImpl.java    From EVCache with Apache License 2.0 6 votes vote down vote up
private <T> Single<T> getData(EVCacheClient client, EVCacheKey evcKey, Transcoder<T> tc, boolean throwException, boolean hasZF, Scheduler scheduler) {
    if (client == null) return Single.error(new IllegalArgumentException("Client cannot be null"));
    if(hashKey.get()) {
        return Single.error(new IllegalArgumentException("Not supported"));
    } else {
        final Transcoder<T> transcoder = (tc == null) ? ((_transcoder == null) ? (Transcoder<T>) client.getTranscoder() : (Transcoder<T>) _transcoder) : tc;
        return client.get(evcKey.getCanonicalKey(client.isDuetClient()), transcoder, throwException, hasZF, scheduler).onErrorReturn(ex -> {
            if (ex instanceof EVCacheReadQueueException) {
                if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheReadQueueException while getting data for APP " + _appName + ", key : " + evcKey + "; hasZF : " + hasZF, ex);
                if (!throwException || hasZF) return null;
                throw sneakyThrow(ex);
            } else if (ex instanceof EVCacheException) {
                if (log.isDebugEnabled() && shouldLog()) log.debug("EVCacheException while getting data for APP " + _appName + ", key : " + evcKey + "; hasZF : " + hasZF, ex);
                if (!throwException || hasZF) return null;
                throw sneakyThrow(ex);
            } else {
                if (log.isDebugEnabled() && shouldLog()) log.debug("Exception while getting data for APP " + _appName + ", key : " + evcKey, ex);
                if (!throwException || hasZF) return null;
                throw sneakyThrow(ex);
            }
        });
    }
}
 
Example #5
Source File: EVCacheClient.java    From EVCache with Apache License 2.0 6 votes vote down vote up
public <T> Single<T> get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF, boolean chunked, Scheduler scheduler)  throws Exception {
    if (chunked) {
        return assembleChunks(key, _throwException, 0, tc, hasZF, scheduler);
    }  else if(shouldHashKey()) {
        final String hKey = getHashedKey(key);
        final Object obj = evcacheMemcachedClient.asyncGet(hKey, evcacheValueTranscoder, null).get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF);
        if(obj instanceof EVCacheValue) {
            final EVCacheValue val = (EVCacheValue)obj;
            if(val == null || !(val.getKey().equals(key))) {
                incrementFailure(EVCacheMetricsFactory.KEY_HASH_COLLISION, Call.GET);
                return null;
            }
            final CachedData cd = new CachedData(val.getFlags(), val.getValue(), CachedData.MAX_SIZE);
            if(tc == null) {
                return Single.just((T)evcacheMemcachedClient.getTranscoder().decode(cd));
            } else {
                return Single.just(tc.decode(cd));
            }
        } else {
            return null;
        }
    } else {
        return evcacheMemcachedClient.asyncGet(key, tc, null)
            .get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF, scheduler);
    }
}
 
Example #6
Source File: MemcacheClient.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Override
public ComposableFuture<Map<K, V>> getBulkAsync(final Iterable<? extends K> keys) {
  final List<String> stringKeys = new ArrayList<>();
  final Map<String, K> keysMap = new HashMap<>();
  try {
    for (final K key : keys) {
      final String stringKey = keyTranslator.translateKey(key);
      stringKeys.add(stringKey);
      keysMap.put(stringKey, key);
    }

    return SpyFutureHelper.fromBulkGet(() -> {
      @SuppressWarnings("unchecked")
      final Transcoder<V> transcoder = (Transcoder<V>) spyClient.getTranscoder();
      return spyClient.asyncGetBulk(stringKeys, transcoder);
    }, keysMap);

  } catch (final Exception e) {
    return fromError(e);
  }
}
 
Example #7
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void addStringIntTMemcacheTranscoderOfT() throws TimeoutException, CacheException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.add(EasyMock.eq("test"), EasyMock.eq(1000), EasyMock.eq("value"), EasyMock.anyObject(Transcoder.class)))
            .andReturn(getFuture(true));
    EasyMock.replay(client, transcoder);
    assertTrue(clientWrapper.add("test", 1000, "value", transcoder));
    EasyMock.verify(client, transcoder);
}
 
Example #8
Source File: MemCachePeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
/**
 * Method to allow CAS 
 * @param <T>
 * @param key
 * @param mutation
 * @param value
 * @return
 */
public static <T> T cas(String key,CASMutation<T> mutation,T value,int expireSecs)
{
	MemcachedClient client = getClient();
	 if (client != null)
	 {
		 Transcoder transcoder = new SerializingTranscoder();
		 // The mutator who'll do all the low-level stuff.
		 // Set number of retries to limit time taken..its not essential this succeeds
		 CASMutator<T> mutator = new CASMutator<>(client, transcoder,MAX_CAS_RETRIES);

		 // This returns whatever value was successfully stored within the
		 // cache -- either the initial list as above, or a mutated existing
		 // one
		 try 
		 {
			 return mutator.cas(hashKey(key), value, expireSecs, mutation);
		 } 
		 catch (Exception e) 
		 {
			 logger.error("Failed up update hits in cache ",e);
			 return null;
		 }
	 }
	 else
		 return null;
}
 
Example #9
Source File: EVCacheImpl.java    From EVCache with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Future<T> getAsynchronous(final String key, final Transcoder<T> tc) throws EVCacheException {
    if (null == key) throw new IllegalArgumentException("Key is null.");

    final boolean throwExc = doThrowException();
    final EVCacheClient client = _pool.getEVCacheClientForRead();
    if (client == null) {
        incrementFastFail(EVCacheMetricsFactory.NULL_CLIENT, Call.ASYNC_GET);
        if (throwExc) throw new EVCacheException("Could not find a client to asynchronously get the data");
        return null; // Fast failure
    }

    return getGetFuture(client, key, tc, throwExc);
}
 
Example #10
Source File: MemcacheClientWrapper.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Transcoder<T> getTranscoder(final CacheTranscoder transcoder) {
    Transcoder<T> transcoderAdapter = (Transcoder<T>) adapters.get(transcoder);
    if (transcoderAdapter == null) {
        transcoderAdapter = (Transcoder<T>) new TranscoderAdapter(transcoder);
        adapters.put(transcoder, transcoderAdapter);
    }

    return transcoderAdapter;
}
 
Example #11
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void addStringIntTMemcacheTranscoderOfT() throws TimeoutException, CacheException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.add(EasyMock.eq("test"), EasyMock.eq(1000), EasyMock.eq("value"), EasyMock.anyObject(Transcoder.class)))
            .andReturn(getFuture(true));
    EasyMock.replay(client, transcoder);
    assertTrue(clientWrapper.add("test", 1000, "value", transcoder));
    EasyMock.verify(client, transcoder);
}
 
Example #12
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getStringMemcacheTranscoderOfT() throws CacheException, TimeoutException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.get(EasyMock.eq("key1"), EasyMock.anyObject(Transcoder.class))).andReturn("test-value");
    EasyMock.replay(client);
    assertEquals("test-value", clientWrapper.get("key1", transcoder));
    EasyMock.verify(client);
}
 
Example #13
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getBulkCollectionOfStringMemcacheTranscoderOfT() throws TimeoutException, CacheException {
    Collection<String> keys = EasyMock.createMock(Collection.class);
    Map<String, Object> results = EasyMock.createMock(Map.class);
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);

    EasyMock.expect(client.getBulk(EasyMock.eq(keys), EasyMock.anyObject(Transcoder.class))).andReturn(results);
    EasyMock.replay(client);
    assertEquals(results, clientWrapper.getBulk(keys, transcoder));
    EasyMock.verify(client);
}
 
Example #14
Source File: EVCacheClientPoolManager.java    From EVCache with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> EVCacheInMemoryCache<T> createInMemoryCache(Transcoder<T> tc, EVCacheImpl impl) {
    final String name = impl.getCachePrefix() == null ? impl.getAppName() : impl.getAppName() + impl.getCachePrefix();
    EVCacheInMemoryCache<T> cache = (EVCacheInMemoryCache<T>) inMemoryMap.get(name);
    if(cache == null) {
        writeLock.lock();
        if((cache = getInMemoryCache(name)) == null) {
            cache = new EVCacheInMemoryCache<T>(impl.getAppName(), tc, impl);
            inMemoryMap.put(name, cache);
        }
        writeLock.unlock();
    }
    return cache;
}
 
Example #15
Source File: EVCacheClient.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public <T> Single<T> get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF, Scheduler scheduler) {
    try {
        if (!validateNode(key, _throwException, Call.GET)) {
            if(ignoreInactiveNodes.get()) {
                incrementFailure(EVCacheMetricsFactory.IGNORE_INACTIVE_NODES, Call.GET);
                return pool.getEVCacheClientForReadExclude(serverGroup).get(key, tc, _throwException, hasZF, enableChunking.get(), scheduler);
            } else {
                return Single.just(null);
            }
        }
        return get(key, tc, _throwException, hasZF, enableChunking.get(), scheduler);
    } catch (Throwable e) {
        return Single.error(e);
    }
}
 
Example #16
Source File: MemcacheClientWrapper.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Transcoder<T> getTranscoder(final CacheTranscoder transcoder) {
    Transcoder<T> transcoderAdapter = (Transcoder<T>) adapters.get(transcoder);
    if (transcoderAdapter == null) {
        transcoderAdapter = (Transcoder<T>) new TranscoderAdapter(transcoder);
        adapters.put(transcoder, transcoderAdapter);
    }

    return transcoderAdapter;
}
 
Example #17
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void setStringIntTMemcacheTranscoderOfT() throws TimeoutException, CacheException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.set(EasyMock.eq("key1"), EasyMock.eq(1), EasyMock.eq("value"), EasyMock.anyObject(Transcoder.class)))
            .andReturn(getFuture(true));
    EasyMock.replay(client);
    assertTrue(clientWrapper.set("key1", 1, "value", transcoder));
    EasyMock.verify(client);
}
 
Example #18
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getStringMemcacheTranscoderOfTLong() throws TimeoutException, CacheException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.asyncGet(EasyMock.eq("key1"), EasyMock.anyObject(Transcoder.class))).andReturn(getFuture("test-value"));
    EasyMock.replay(client);
    assertEquals("test-value", clientWrapper.get("key1", transcoder, 100));
    EasyMock.verify(client);
}
 
Example #19
Source File: EVCacheClient.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public <T> Future<T> asyncGet(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF)
        throws Exception {
    if (enableChunking.get()) throw new EVCacheException(
            "This operation is not supported as chunking is enabled on this EVCacheClient.");
    if (!validateNode(key, _throwException, Call.ASYNC_GET)) return null;
    if (tc == null) tc = (Transcoder<T>) getTranscoder();
    if(shouldHashKey()) {
        final String hKey = getHashedKey(key);
        return evcacheMemcachedClient.asyncGet(hKey, tc, null);
    } else {
        return evcacheMemcachedClient.asyncGet(key, tc, null);
    }
}
 
Example #20
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getStringMemcacheTranscoderOfTLong() throws TimeoutException, CacheException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.asyncGet(EasyMock.eq("key1"), EasyMock.anyObject(Transcoder.class))).andReturn(getFuture("test-value"));
    EasyMock.replay(client);
    assertEquals("test-value", clientWrapper.get("key1", transcoder, 100));
    EasyMock.verify(client);
}
 
Example #21
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getBulkCollectionOfStringMemcacheTranscoderOfT() throws TimeoutException, CacheException {
    Collection<String> keys = EasyMock.createMock(Collection.class);
    Map<String, Object> results = EasyMock.createMock(Map.class);
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);

    EasyMock.expect(client.getBulk(EasyMock.eq(keys), EasyMock.anyObject(Transcoder.class))).andReturn(results);
    EasyMock.replay(client);
    assertEquals(results, clientWrapper.getBulk(keys, transcoder));
    EasyMock.verify(client);
}
 
Example #22
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void setStringIntTMemcacheTranscoderOfT() throws TimeoutException, CacheException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.set(EasyMock.eq("key1"), EasyMock.eq(1), EasyMock.eq("value"), EasyMock.anyObject(Transcoder.class)))
            .andReturn(getFuture(true));
    EasyMock.replay(client);
    assertTrue(clientWrapper.set("key1", 1, "value", transcoder));
    EasyMock.verify(client);
}
 
Example #23
Source File: MemcacheClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
@Override
public ComposableFuture<V> getAsync(final K key) {
  return SpyFutureHelper.fromGet(() -> {
    @SuppressWarnings("unchecked")
    final Transcoder<V> transcoder = (Transcoder<V>) spyClient.getTranscoder();
    return spyClient.asyncGet(keyTranslator.translateKey(key), transcoder);
  });
}
 
Example #24
Source File: MemcacheClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
private ComposableFuture<CASResponse> casUpdate(final K key, final EntryMapper<K, V> mapper) {
  try {
    final String cacheKey = keyTranslator.translateKey(key);
    final ComposableFuture<CASValue<V>> getFutureValue = SpyFutureHelper.fromCASValue(() -> {
      @SuppressWarnings("unchecked")
      final Transcoder<V> transcoder = (Transcoder<V>) spyClient.getTranscoder();
      return spyClient.asyncGets(cacheKey, transcoder);
    });

    return getFutureValue.flatMap(result -> {
      final V newValue = result == null ? mapper.map(key, null) : mapper.map(key, result.getValue());
      if (newValue == null) {
        return fromValue(CASResponse.OBSERVE_ERROR_IN_ARGS);
      }

      if (result != null) {
        return SpyFutureHelper.fromCASResponse(() -> spyClient.asyncCAS(cacheKey, result.getCas(), newValue));

      } else {
        final ComposableFuture<Boolean> addResponse = SpyFutureHelper.fromOperation(
          () -> spyClient.add(cacheKey, expirationSpyUnits, newValue));

        return addResponse.map(result1 -> {
          if (result1 == Boolean.TRUE) {
            return CASResponse.OK;
          } else {
            return CASResponse.EXISTS;
          }
        });
      }
    });
  } catch (final Exception e) {
    return fromError(e);
  }
}
 
Example #25
Source File: EVCacheClient.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public <T> T get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF) throws Exception {
    if (!validateNode(key, _throwException, Call.GET)) {
        if(ignoreInactiveNodes.get()) {
            incrementFailure(EVCacheMetricsFactory.IGNORE_INACTIVE_NODES, Call.GET);
            return pool.getEVCacheClientForReadExclude(serverGroup).get(key, tc, _throwException, hasZF, enableChunking.get());
        } else {
            return null;
        }
    }
    return get(key, tc, _throwException, hasZF, enableChunking.get());
}
 
Example #26
Source File: EVCacheImpl.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public <T> T get(String key, Transcoder<T> tc) throws EVCacheException {
    if (null == key) throw new IllegalArgumentException("Key cannot be null");
    final EVCacheKey evcKey = getEVCacheKey(key);
    if (_useInMemoryCache.get()) {
        T value = null;
        try {
            final Transcoder<T> transcoder = (tc == null) ? ((_transcoder == null) ? (Transcoder<T>) _pool.getEVCacheClientForRead().getTranscoder() : (Transcoder<T>) _transcoder) : tc;
            value = (T) getInMemoryCache(transcoder).get(evcKey);
        } catch (ExecutionException e) {
            final boolean throwExc = doThrowException();
            if(throwExc) {
                if(e.getCause() instanceof DataNotFoundException) {
                    return null;
                }
                if(e.getCause() instanceof EVCacheException) {
                    if (log.isDebugEnabled() && shouldLog()) log.debug("ExecutionException while getting data from InMemory Cache", e);
                    throw (EVCacheException)e.getCause();
                }
                throw new EVCacheException("ExecutionException", e);
            }
        }
        if (log.isDebugEnabled() && shouldLog()) log.debug("Value retrieved from inmemory cache for APP " + _appName + ", key : " + evcKey + (log.isTraceEnabled() ? "; value : " + value : ""));
        if (value != null) {
            if (log.isDebugEnabled() && shouldLog()) log.debug("Value retrieved from inmemory cache for APP " + _appName + ", key : " + evcKey + (log.isTraceEnabled() ? "; value : " + value : ""));
            return value;
        } else {
            if (log.isInfoEnabled() && shouldLog()) log.info("Value not_found in inmemory cache for APP " + _appName + ", key : " + evcKey + "; value : " + value );
        }
    }
    return doGet(evcKey, tc);
}
 
Example #27
Source File: EVCacheInMemoryCache.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public EVCacheInMemoryCache(String appName, Transcoder<T> tc, EVCacheImpl impl) {
    this.appName = appName;
    this.tc = tc;
    this.impl = impl;

    this._cacheDuration = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".inmemory.expire.after.write.duration.ms", Integer.class).orElseGet(appName + ".inmemory.cache.duration.ms").orElse(0);
    this._cacheDuration.subscribe((i) -> setupCache());
    this._exireAfterAccessDuration = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".inmemory.expire.after.access.duration.ms", Integer.class).orElse(0);
    this._exireAfterAccessDuration.subscribe((i) -> setupCache());;

    this._refreshDuration = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".inmemory.refresh.after.write.duration.ms", Integer.class).orElse(0);
    this._refreshDuration.subscribe((i) -> setupCache());

    this._cacheSize = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".inmemory.cache.size", Integer.class).orElse(100);
    this._cacheSize.subscribe((i) -> setupCache());

    this._poolSize = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".thread.pool.size", Integer.class).orElse(5);
    this._poolSize.subscribe((i) -> initRefreshPool());

    final List<Tag> tags = new ArrayList<Tag>(3);
    tags.addAll(impl.getTags());
    tags.add(new BasicTag(EVCacheMetricsFactory.METRIC, "size"));

    this.sizeId = EVCacheMetricsFactory.getInstance().getId(EVCacheMetricsFactory.IN_MEMORY, tags);
    setupCache();
    setupMonitoring(appName);
}
 
Example #28
Source File: SpyMemcachedAdapter.java    From hibernate4-memcached with Apache License 2.0 5 votes vote down vote up
private Transcoder<Object> createTranscoder(OverridableReadOnlyProperties properties, String transcoderClassProperty) {
    try {
        @SuppressWarnings("unchecked")
        Class<InitializableTranscoder<Object>> transcoderClass = (Class<InitializableTranscoder<Object>>) Class.forName(transcoderClassProperty);
        InitializableTranscoder<Object> transcoder = transcoderClass.newInstance();
        transcoder.init(properties);
        return transcoder;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create Transcoder object.", e);
    }
}
 
Example #29
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getStringMemcacheTranscoderOfT() throws CacheException, TimeoutException {
    CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
    EasyMock.expect(client.get(EasyMock.eq("key1"), EasyMock.anyObject(Transcoder.class))).andReturn("test-value");
    EasyMock.replay(client);
    assertEquals("test-value", clientWrapper.get("key1", transcoder));
    EasyMock.verify(client);
}
 
Example #30
Source File: EVCacheImpl.java    From EVCache with Apache License 2.0 4 votes vote down vote up
EVCacheImpl(String appName, String cacheName, int timeToLive, Transcoder<?> transcoder, boolean enableZoneFallback,
        boolean throwException, EVCacheClientPoolManager poolManager) {
    this._appName = appName;
    this._cacheName = cacheName;

    if(_cacheName != null && _cacheName.length() > 0) {
        for(int i = 0; i < cacheName.length(); i++) {
            if(Character.isWhitespace(cacheName.charAt(i))){
                throw new IllegalArgumentException("Cache Prefix ``" + cacheName  + "`` contains invalid character at position " + i );
            }
        }
    }

    this._timeToLive = timeToLive;
    this._transcoder = transcoder;
    this._zoneFallback = enableZoneFallback;
    this._throwException = throwException;

    tags = new ArrayList<Tag>(3);
    EVCacheMetricsFactory.getInstance().addAppNameTags(tags, _appName);
    if(_cacheName != null && _cacheName.length() > 0) tags.add(new BasicTag(EVCacheMetricsFactory.PREFIX, _cacheName));

    final String _metricName = (_cacheName == null) ? _appName : _appName + "." + _cacheName;
    _metricPrefix = _appName + "-";
    this._poolManager = poolManager;
    this._pool = poolManager.getEVCacheClientPool(_appName);
    final PropertyRepository propertyRepository = poolManager.getEVCacheConfig().getPropertyRepository();
    _throwExceptionFP = propertyRepository.get(_metricName + ".throw.exception", Boolean.class).orElseGet(_appName + ".throw.exception").orElse(false);
    _zoneFallbackFP = propertyRepository.get(_metricName + ".fallback.zone", Boolean.class).orElseGet(_appName + ".fallback.zone").orElse(true);
    _bulkZoneFallbackFP = propertyRepository.get(_appName + ".bulk.fallback.zone", Boolean.class).orElse(true);
    _bulkPartialZoneFallbackFP = propertyRepository.get(_appName+ ".bulk.partial.fallback.zone", Boolean.class).orElse(true);
    if(_cacheName == null) {
        _useInMemoryCache = propertyRepository.get(_appName + ".use.inmemory.cache", Boolean.class).orElseGet("evcache.use.inmemory.cache").orElse(false);
    } else {
        _useInMemoryCache = propertyRepository.get(_appName + "." + _cacheName + ".use.inmemory.cache", Boolean.class).orElseGet(_appName + ".use.inmemory.cache").orElseGet("evcache.use.inmemory.cache").orElse(false);
    }
    _eventsUsingLatchFP = propertyRepository.get(_appName + ".events.using.latch", Boolean.class).orElseGet("evcache.events.using.latch").orElse(false);
     maxReadDuration = propertyRepository.get(_appName + ".max.read.duration.metric", Integer.class).orElseGet("evcache.max.write.duration.metric").orElse(20);
     maxWriteDuration = propertyRepository.get(_appName + ".max.write.duration.metric", Integer.class).orElseGet("evcache.max.write.duration.metric").orElse(50);
     ignoreTouch = propertyRepository.get(appName + ".ignore.touch", Boolean.class).orElse(false);


    this.hashKey = propertyRepository.get(appName + ".hash.key", Boolean.class).orElse(false);
    this.hashingAlgo = propertyRepository.get(appName + ".hash.algo", String.class).orElse("siphash24");
    this.autoHashKeys = propertyRepository.get(_appName + ".auto.hash.keys", Boolean.class).orElseGet("evcache.auto.hash.keys").orElse(false);
    this.evcacheValueTranscoder = new EVCacheTranscoder();
    evcacheValueTranscoder.setCompressionThreshold(Integer.MAX_VALUE);

    // default max key length is 200, instead of using what is defined in MemcachedClientIF.MAX_KEY_LENGTH (250). This is to accommodate
    // auto key prepend with appname for duet feature.
    this.maxKeyLength = propertyRepository.get(_appName + ".max.key.length", Integer.class).orElseGet("evcache.max.key.length").orElse(200);

    // if alias changes, refresh my pool to point to the correct alias app
    this.alias = propertyRepository.get("EVCacheClientPoolManager." + appName + ".alias", String.class);
    this.alias.subscribe(i -> {
        this._pool = poolManager.getEVCacheClientPool(_appName);
    });

    _pool.pingServers();
    
    setupMonitoring();
}