net.spy.memcached.MemcachedClient Java Examples

The following examples show how to use net.spy.memcached.MemcachedClient. 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: IntegrationJUnitTest.java    From gemfirexd-oss with Apache License 2.0 7 votes vote down vote up
public void testGemFireProperty() throws Exception {
  Properties props = new Properties();
  final int port = AvailablePortHelper.getRandomAvailableTCPPort();
  props.setProperty("memcached-port", port+"");
  CacheFactory cf = new CacheFactory(props);
  Cache cache = cf.create();
  
  MemcachedClient client = new MemcachedClient(
      new InetSocketAddress(SocketCreator.getLocalHost(), port));
  Future<Boolean> f = client.add("key", 10, "myStringValue");
  assertTrue(f.get());
  Future<Boolean> f1 = client.add("key1", 10, "myStringValue1");
  assertTrue(f1.get());
  
  assertEquals("myStringValue", client.get("key"));
  assertEquals("myStringValue1", client.get("key1"));
  assertNull(client.get("nonExistentkey"));
  cache.close();
}
 
Example #2
Source File: ExceptionSwallowingMemcachedClient.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Autowired
public ExceptionSwallowingMemcachedClient(GlobalConfigHandler globalConfigHandler, ZkCuratorHandler zkCuratorHandler) throws Exception {
    logger.info("Initializing...");
    Stat stat = zkCuratorHandler.getCurator().checkExists().forPath(ZK_CONFIG_KEY_MEMCACHED_SERVERS_FPATH);
    if (stat != null) 
    {
        ObjectMapper mapper = new ObjectMapper();
        byte[] bytes = zkCuratorHandler.getCurator().getData().forPath(ZK_CONFIG_KEY_MEMCACHED_SERVERS_FPATH);
        MemcacheConfig config = mapper.readValue(bytes,MemcacheConfig.class);
        logger.info(config.toString());
        memcachedClient = new MemcachedClient(new ConnectionFactoryBuilder(new DefaultConnectionFactory()).setOpTimeout(MEMCACHE_OP_TIMEOUT).build(),
                AddrUtil.getAddresses(config.servers));
        logger.info(String.format("MemcachedClient initialized using %s[%s]", ZK_CONFIG_KEY_MEMCACHED_SERVERS, config.servers));
        
        MemCachePeer.initialise(config.servers,config.numClients);
    }

    if (memcachedClient == null) {
        throw new Exception("*Warning* Memcached NOT initialized!");
    }
    globalConfigHandler.addSubscriber(ZK_CONFIG_KEY_MEMCACHED_SERVERS, this);
}
 
Example #3
Source File: MemCachePeer.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
public static CASValue gets(String key)
{
	MemcachedClient client = getClient();
	if (client != null)
	{
	try
	{
		return client.gets(hashKey(key));
	}
	catch (Exception ex)
	{
		logger.error("Memcache get exeption ",ex);
		return null;
	}
	}
	else
		return null;
}
 
Example #4
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testPrepend() throws Exception {
  MemcachedClient client = bootstrapClient();
  Future<Boolean> b = client.prepend(0, "key", "prepended");
  assertTrue(b.get());
  assertEquals("prependedmyStringValue", client.get("key"));
  b = client.prepend(0, "prependkey", "val");
  assertFalse(b.get());
  assertNull(client.get("prependkey"));
}
 
Example #5
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testMultiGet() throws Exception {
  MemcachedClient client = bootstrapClient();
  Map<String, Object> val = client.getBulk("key", "key1");
  assertEquals(2, val.size());
  assertEquals("myStringValue", val.get("key"));
  assertEquals("myStringValue1", val.get("key1"));
  client.add("Hello", 0, "World");
  Thread.sleep(1100);
  assertEquals("World", client.get("Hello"));
}
 
Example #6
Source File: SpyMemcacheIT.java    From hibernate-l2-memcached with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    client = new MemcachedClient(AddrUtil.getAddresses("localhost:11211"));
    Properties properties = new Properties();
    PropertiesHelper props = new PropertiesHelper(properties);
    Config config = new Config(props);
    cache = new MemcachedCache("MemcachedCacheTest", new SpyMemcache(client), config);
}
 
Example #7
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private MemcachedClient bootstrapClient() throws IOException,
    UnknownHostException, InterruptedException, ExecutionException {
  MemcachedClient client = createMemcachedClient();
  Future<Boolean> f = client.add("key", 10, "myStringValue");
  f.get();
  Future<Boolean> f1 = client.add("key1", 10, "myStringValue1");
  f1.get();
  return client;
}
 
Example #8
Source File: MemcacheClientTest.java    From ob1k with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() throws IOException {
  final ConnectionFactory cf = new ConnectionFactoryBuilder()
    .setProtocol(ConnectionFactoryBuilder.Protocol.TEXT)
    .setTranscoder(new WhalinTranscoder())
    .setOpTimeout(1000)
    .build();

  spyClient = new MemcachedClient(cf, Collections.singletonList(new InetSocketAddress("localhost", MEMCACHED_PORT)));
}
 
Example #9
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testCas() throws Exception {
  MemcachedClient client = bootstrapClient();
  client.add("caskey", 10, "casValue").get();
  CASValue<Object> val = client.gets("caskey");
  assertEquals("casValue", val.getValue());
  CASResponse r = client.cas("caskey", val.getCas(), "newValue");
  assertEquals(CASResponse.OK, r);
  r = client.cas("caskey", val.getCas(), "newValue2");
  assertEquals(CASResponse.EXISTS, r);
}
 
Example #10
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testGets() throws Exception {
  MemcachedClient client = bootstrapClient();
  client.add("getskey", 10, "casValue").get();
  CASValue<Object> val = client.gets("getskey");
  long oldCas = val.getCas();
  assertEquals("casValue", val.getValue());
  client.replace("getskey", 10, "myNewVal").get();
  val = client.gets("getskey");
  assertEquals(oldCas + 1, val.getCas());
  assertEquals("myNewVal", val.getValue());
}
 
Example #11
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testDecr() throws Exception {
  MemcachedClient client = bootstrapClient();
  client.add("decrkey", 10, 99).get();
  assertEquals(95, client.decr("decrkey", 4));
  assertEquals(94, client.decr("decrkey", 1));
  assertEquals(-1, client.decr("decrkey1", 77));
}
 
Example #12
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testIncr() throws Exception {
  MemcachedClient client = bootstrapClient();
  client.add("incrkey", 10, 99).get();
  assertEquals(104, client.incr("incrkey", 5));
  assertEquals(105, client.incr("incrkey", 1));
  assertEquals(-1, client.incr("inckey1", 10));
}
 
Example #13
Source File: MemCachePeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public static void delete(String key)
{
	MemcachedClient client = getClient();
	if (client != null)
	try
	{
		client.delete(hashKey(key));
	}
	catch (Exception ex)
	{
		logger.error("Memcache delete exeption ",ex);
	}
}
 
Example #14
Source File: SpymemcachedFactoryTest.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Test of create method, of class SpymemcachedUtil.
 */
@Test
public void testCreate_5args() {
    System.out.println("create");
    ConnectionFactoryBuilder.Protocol protocol = ConnectionFactoryBuilder.Protocol.BINARY;
    String user = "";
    String pass = "";
    String[] authMechanisms = new String[]{"PLAIN"};
    MemcachedClient result = SpymemcachedFactory.create(HOST, protocol, user, pass, authMechanisms);
    assertNotNull(result);
    result.shutdown();
}
 
Example #15
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testFlush() throws Exception {
  MemcachedClient client = bootstrapClient();
  Future<Boolean> b = client.flush();
  assertTrue(b.get());
  assertNull(client.get("key"));
  assertNull(client.get("key1"));
}
 
Example #16
Source File: MemcacheClientFactoryImpl.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Override
public CacheClient create(final List<InetSocketAddress> addrs, final CacheConfiguration conf) throws IOException {
    // currently its works because this factory creates clients with the same connection settings, only memcached
    // addresses can be changed
    if (connectionFactory == null) {
        ElastiCacheConfiguration elasticacheConf = null;
        if (conf instanceof ElastiCacheConfiguration) {
            elasticacheConf = (ElastiCacheConfiguration) conf;
        }
        
        if (elasticacheConf != null && Boolean.TRUE.equals(elasticacheConf.getUseAutoDiscovery())) {
            // there is no way to use custom client settings and auto discovery together
            LOGGER.info("All cache settings will be ignored because useAutoDiscovery is true");
            return new MemcacheClientWrapper(new MemcachedClient(addrs));
        }
        
        
        ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();

        if (conf.isConsistentHashing()) {
            builder.setHashAlg(DefaultHashAlgorithm.KETAMA_HASH);
            builder.setLocatorType(Locator.CONSISTENT);
        }

        builder.setProtocol(conf.isUseBinaryProtocol() ? Protocol.BINARY : Protocol.TEXT);
        if (conf.getOperationTimeout() != null) {
            builder.setOpTimeout(conf.getOperationTimeout());
        }

        if (elasticacheConf != null) {
            setProviderSpecificSettings(builder, elasticacheConf);
        }

        connectionFactory = builder.build();
    }

    return new MemcacheClientWrapper(new MemcachedClient(connectionFactory, addrs));
}
 
Example #17
Source File: SpymemcachedFactory.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Create a memcached client with pippo settings.
 *
 * @param settings pippo settings
 * @return memcached client
 */
public static final MemcachedClient create(final PippoSettings settings) {
    String host = settings.getString(HOST, "localhost:11211");
    String prot = settings.getString(PROT, "BINARY");
    Protocol protocol = Protocol.valueOf(prot);
    String user = settings.getString(USER, "");
    String pass = settings.getString(PASS, "");
    List<String> autM = settings.getStrings(AUTM);
    String[] mechanisms = autM.toArray(new String[autM.size()]);
    return create(host, protocol, user, pass, mechanisms);
}
 
Example #18
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testReplace() throws Exception {
  MemcachedClient client = bootstrapClient();
  Future<Boolean> b = client.replace("key", 10, "newVal");
  assertTrue(b.get());
  b = client.replace("nonExistentkey", 10, "val");
  assertFalse(b.get());
  b = client.replace("key", 10, "myStringValue");
  assertTrue(b.get());
}
 
Example #19
Source File: MemCachePeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public static void put(String key,Object obj)
{
	MemcachedClient client = getClient();
	if (client != null)
	try
	{
		client.set(hashKey(key), 0, obj);
	}
	catch (Exception ex)
	{
		logger.error("Memcache put exeption ",ex);
	}
}
 
Example #20
Source File: MemCachePeer.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public static void put(String key,Object obj,int expireSeconds)
{
	MemcachedClient client = getClient();
	if (client != null)
		try
		{
			client.set(hashKey(key), expireSeconds, obj);
		}
		catch (Exception ex)
		{
			logger.error("Memcache put expire exeption ",ex);
		}
}
 
Example #21
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testPutGet() throws Exception {
  MemcachedClient client = createMemcachedClient();
  Future<Boolean> f = client.add("key", 10, "myStringValue");
  assertTrue(f.get());
  Future<Boolean> f1 = client.add("key1", 10, "myStringValue1");
  assertTrue(f1.get());
  assertEquals("myStringValue", client.get("key"));
  assertEquals("myStringValue1", client.get("key1"));
  assertNull(client.get("nonExistentkey"));
  // zero exp
  f = client.add("Hello", 0, "World");
  Thread.sleep(1100);
  assertEquals("World", client.get("Hello"));
}
 
Example #22
Source File: DomainObjectsAsValuesJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testGetPutDomainObject() throws Exception {
  MemcachedClient client = new MemcachedClient(
      new InetSocketAddress(SocketCreator.getLocalHost(), PORT));
  Customer c = new Customer("name0", "addr0");
  Customer c1 = new Customer("name1", "addr1");
  Future<Boolean> f = client.add("keyObj", 10, c);
  assertTrue(f.get());
  Future<Boolean> f1 = client.add("key1", 10, c1);
  assertTrue(f1.get());
  assertEquals(c, client.get("keyObj"));
  assertEquals(c1, client.get("key1"));
  assertNull(client.get("nonExistentkey"));
}
 
Example #23
Source File: GemcachedBinaryClientJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
protected MemcachedClient createMemcachedClient() throws IOException,
    UnknownHostException {
  List<InetSocketAddress> addrs = new ArrayList<InetSocketAddress>();
  addrs.add(new InetSocketAddress(SocketCreator.getLocalHost(), PORT));
  MemcachedClient client = new MemcachedClient(new BinaryConnectionFactory(), addrs);
  return client;
}
 
Example #24
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 #25
Source File: TransientElasticacheDataConnectionTest.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    memcachedClient = mock(MemcachedClient.class);

    stub(memcachedClient.get("key1")).toReturn("value1");
    stub(memcachedClient.get("key2")).toReturn("value2");
    OperationFuture<Boolean> mockedFuture = mock(OperationFuture.class);
    stub(memcachedClient.add("keyAdd", 3600, "valueadd")).toReturn(mockedFuture);
}
 
Example #26
Source File: MemcachePoolMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public void activateService()
    throws Exception
{
    MemcacheConfiguration config = configuration.get();
    expiration = ( config.expiration().get() == null )
                 ? 3600
                 : config.expiration().get();
    String addresses = ( config.addresses().get() == null )
                       ? "localhost:11211"
                       : config.addresses().get();
    Protocol protocol = ( config.protocol().get() == null )
                        ? Protocol.TEXT
                        : Protocol.valueOf( config.protocol().get().toUpperCase() );
    String username = config.username().get();
    String password = config.password().get();
    String authMech = config.authMechanism().get() == null
                      ? "PLAIN"
                      : config.authMechanism().get();

    ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
    builder.setProtocol( protocol );
    if( username != null && !username.isEmpty() )
    {
        String[] authType = { authMech };
        AuthDescriptor to = new AuthDescriptor( authType, new PlainCallbackHandler( username, password ) );
        builder.setAuthDescriptor( to );
    }

    client = new MemcachedClient( builder.build(), AddrUtil.getAddresses( addresses ) );
}
 
Example #27
Source File: ConfigureElasticache.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Bean(name = "memcachedClient")
public MemcachedClient createMemcachedClient() throws IOException {
    try {
        log.info("Starting an instance of memcache client towards elasticache cluster");
        return new MemcachedClient(new InetSocketAddress(hostname, port));
    } catch (IOException e) {
        log.error("Could not initilise connection to elasticache cluster", e);
        return null;
    }

}
 
Example #28
Source File: MemcacheImpl.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
MemcacheImpl( MemcachedClient client, String cacheId, Class<T> valueType, int expiration )
{
    this.client = client;
    this.cacheId = cacheId;
    this.cachePrefix = cacheId + "." + INSTANCES.incrementAndGet() + ".";
    this.valueType = valueType;
    this.expiration = expiration;
}
 
Example #29
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private MemcachedClient bootstrapClient() throws IOException,
    UnknownHostException, InterruptedException, ExecutionException {
  MemcachedClient client = createMemcachedClient();
  Future<Boolean> f = client.add("key", 10, "myStringValue");
  f.get();
  Future<Boolean> f1 = client.add("key1", 10, "myStringValue1");
  f1.get();
  return client;
}
 
Example #30
Source File: GemcachedDevelopmentJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testCas() throws Exception {
  MemcachedClient client = bootstrapClient();
  client.add("caskey", 10, "casValue").get();
  CASValue<Object> val = client.gets("caskey");
  assertEquals("casValue", val.getValue());
  CASResponse r = client.cas("caskey", val.getCas(), "newValue");
  assertEquals(CASResponse.OK, r);
  r = client.cas("caskey", val.getCas(), "newValue2");
  assertEquals(CASResponse.EXISTS, r);
}