net.spy.memcached.MemcachedClient类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(12.4k)|赞(0)|评价(0)|浏览(184)

本文整理了Java中net.spy.memcached.MemcachedClient类的一些代码示例,展示了MemcachedClient类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MemcachedClient类的具体详情如下:
包路径:net.spy.memcached.MemcachedClient
类名称:MemcachedClient

MemcachedClient介绍

[英]Client to a memcached server. Basic usage

MemcachedClient c=new MemcachedClient( 
new InetSocketAddress("hostname", portNum)); 
// Store a value (async) for one hour 
c.set("someKey", 3600, someObject); 
// Retrieve a value. 
Object myObject=c.get("someKey");

Advanced Usage

MemcachedClient may be processing a great deal of asynchronous messages or possibly dealing with an unreachable memcached, which may delay processing. If a memcached is disabled, for example, MemcachedConnection will continue to attempt to reconnect and replay pending operations until it comes back up. To prevent this from causing your application to hang, you can use one of the asynchronous mechanisms to time out a request and cancel the operation to the server.

// Get a memcached client connected to several servers 
// over the binary protocol 
MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(), 
AddrUtil.getAddresses("server1:11211 server2:11211")); 
// Try to get a value, for up to 5 seconds, and cancel if it 
// doesn't return 
Object myObj = null; 
Future<Object> f = c.asyncGet("someKey"); 
try { 
myObj = f.get(5, TimeUnit.SECONDS); 
// throws expecting InterruptedException, ExecutionException 
// or TimeoutException 
} catch (Exception e) {  /*  / 
// Since we don't need this, go ahead and cancel the operation. 
// This is not strictly necessary, but it'll save some work on 
// the server.  It is okay to cancel it if running. 
f.cancel(true); 
// Do other timeout related stuff 
}

[中]客户端到memcached服务器。基本用法

MemcachedClient c=new MemcachedClient( 
new InetSocketAddress("hostname", portNum)); 
// Store a value (async) for one hour 
c.set("someKey", 3600, someObject); 
// Retrieve a value. 
Object myObject=c.get("someKey");

高级用法
MemcachedClient可能正在处理大量异步消息,或者可能正在处理无法访问的memcached,这可能会延迟处理。例如,如果memcached被禁用,MemcachedConnection将继续尝试重新连接并重播挂起的操作,直到它恢复。为了防止这导致应用程序挂起,可以使用其中一种异步机制来超时请求并取消对服务器的操作。

// Get a memcached client connected to several servers 
// over the binary protocol 
MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(), 
AddrUtil.getAddresses("server1:11211 server2:11211")); 
// Try to get a value, for up to 5 seconds, and cancel if it 
// doesn't return 
Object myObj = null; 
Future<Object> f = c.asyncGet("someKey"); 
try { 
myObj = f.get(5, TimeUnit.SECONDS); 
// throws expecting InterruptedException, ExecutionException 
// or TimeoutException 
} catch (Exception e) {  /*  / 
// Since we don't need this, go ahead and cancel the operation. 
// This is not strictly necessary, but it'll save some work on 
// the server.  It is okay to cancel it if running. 
f.cancel(true); 
// Do other timeout related stuff 
}

代码示例

代码示例来源:origin: apache/incubator-druid

@Override
 public MemcachedClientIF get()
 {
  try {
   return new MemcachedClient(connectionFactory, hosts);
  }
  catch (IOException e) {
   log.error(e, "Unable to create memcached client");
   throw Throwables.propagate(e);
  }
 }
}

代码示例来源:origin: aol/micro-server

@Override
public Optional<V> get(String key) {
  return (Optional<V>) Optional.ofNullable(memcachedClient.get(key));
}

代码示例来源:origin: ninjaframework/ninja

public boolean safeDelete(String key) {
  Future<Boolean> future = client.delete(key);
  try {
    return future.get(1, TimeUnit.SECONDS);
  } catch (Exception e) {
    future.cancel(false);
  }
  return false;
}

代码示例来源:origin: Netflix/EVCache

public Map<SocketAddress, Map<String, String>> getStats(String cmd) {
  if(config.isRendInstance()) {
    List<InetSocketAddress> udsproxyInetSocketAddress = new ArrayList<InetSocketAddress>(memcachedNodesInZone.size());
    for(InetSocketAddress address : memcachedNodesInZone) {
      udsproxyInetSocketAddress.add(new InetSocketAddress(address.getHostName(), config.getUdsproxyMemcachedPort()));
    }
    
    MemcachedClient mc = null;
    try {
      mc = new MemcachedClient(connectionFactory, udsproxyInetSocketAddress);
      return mc.getStats(cmd);
    } catch(Exception ex) {
      
    } finally {
      if(mc != null) mc.shutdown();
    }
    return Collections.<SocketAddress, Map<String, String>>emptyMap();
  } else {
    return evcacheMemcachedClient.getStats(cmd);
  }
}

代码示例来源:origin: qiujiayu/AutoLoadCache

@Override
public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException {
  if (null == memcachedClient || null == keys || keys.isEmpty()) {
    return;
  }
  String hfield;
  for (CacheKeyTO cacheKeyTO : keys) {
    if (null == cacheKeyTO) {
      continue;
    }
    String cacheKey = cacheKeyTO.getCacheKey();
    if (null == cacheKey || cacheKey.isEmpty()) {
      continue;
    }
    hfield = cacheKeyTO.getHfield();
    if (null != hfield && hfield.length() > 0) {
      throw new RuntimeException("memcached does not support hash cache.");
    }
    try {
      String allKeysPattern = "*";
      if (allKeysPattern.equals(cacheKey)) {
        memcachedClient.flush();
      } else {
        memcachedClient.delete(cacheKey);
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }
}

代码示例来源:origin: jooby-project/jooby

@SuppressWarnings("unchecked")
@Override
public Session get(final Builder builder) {
 String key = key(builder.sessionId());
 Map<String, String> attrs = (Map<String, String>) memcached.get(key);
 if (attrs == null || attrs.size() == 0) {
  // expired
  return null;
 }
 // touch session
 memcached.touch(key, timeout);
 return builder
   .accessedAt(Long.parseLong(attrs.remove("_accessedAt")))
   .createdAt(Long.parseLong(attrs.remove("_createdAt")))
   .savedAt(Long.parseLong(attrs.remove("_savedAt")))
   .set(attrs)
   .build();
}

代码示例来源:origin: org.infinispan/infinispan-compatibility-mode-it

public void testMemcachedPutEmbeddedGet() throws Exception {
 // 1. Put with Memcached
 for (int i = 0; i != numEntries; i++) {
   Future<Boolean> f = cacheFactory2.getMemcachedClient().set("k" + i, 0, "v" + i);
   assertTrue(f.get(60, TimeUnit.SECONDS));
 }
 // 2. Get with Embedded from a different node
 for (int i = 0; i != numEntries; i++) {
   assertEquals("v" + i, cacheFactory1.getEmbeddedCache().get("k" + i));
   cacheFactory1.getEmbeddedCache().remove("k" + i);
 }
}

代码示例来源:origin: ninjaframework/ninja

public Object get(String key) {
  Future<Object> future = client.asyncGet(key, tc);
  try {
    return future.get(1, TimeUnit.SECONDS);
  } catch (Exception e) {
    future.cancel(false);
  }
  return null;
}

代码示例来源:origin: ninjaframework/ninja

public boolean safeSet(String key, Object value, int expiration) {
  Future<Boolean> future = client.set(key, expiration, value, tc);
  try {
    return future.get(1, TimeUnit.SECONDS);
  } catch (Exception e) {
    future.cancel(false);
  }
  return false;
}

代码示例来源:origin: ninjaframework/ninja

public boolean safeAdd(String key, Object value, int expiration) {
  Future<Boolean> future = client.add(key, expiration, value, tc);
  try {
    return future.get(1, TimeUnit.SECONDS);
  } catch (Exception e) {
    future.cancel(false);
  }
  return false;
}

代码示例来源:origin: magro/memcached-session-manager

@Test
public void testInvalidNonStickySessionDoesNotCallOnBackupWithoutLoadedSessionIssue137() throws Exception {
  _service.setStickyInternal( false );
  _service.setLockingMode( LockingMode.NONE, null, false );
  _service.startInternal(new MemcachedStorageClient(_memcachedMock)); // we must put in our mock again
  final String sessionId = "nonStickySessionToTimeOut-n1";
  // For findSession needed
  final Request requestMock = mock(Request.class);
  when(requestMock.getNote(eq(RequestTrackingContextValve.INVOKED))).thenReturn(Boolean.TRUE);
  _service.getTrackingHostValve().storeRequestThreadLocal(requestMock);
  final MemcachedBackupSession session = _service.findSession(sessionId);
  assertNull(session);
  _service.backupSession( sessionId, false, null ).get();
  // check that validity info is not loaded - this would trigger the
  // WARNING: Found no validity info for session id ...
  final String validityKey = new SessionIdFormat().createValidityInfoKeyName( sessionId );
  verify( _memcachedMock, times( 0 ) ).get( eq( validityKey ) );
}

代码示例来源:origin: magro/memcached-session-manager

when( _memcachedMock.get( eq( validityKey ), any ( Transcoder.class) ) ).thenReturn( validityData );
when( futureMock.get() ).thenReturn( Boolean.FALSE );
when( futureMock.get( anyInt(), any( TimeUnit.class ) ) ).thenReturn( Boolean.FALSE );
when( _memcachedMock.add( any( String.class ), anyInt(), any(), any( Transcoder.class ) ) ).thenReturn( futureMock );
_service.backupSession( sessionId, false, "unused" ).get();
verify( _memcachedMock, times( 1 ) ).set( eq( validityKey ), eq( 0 ), any(), any( Transcoder.class ) );
verify( _memcachedMock, times( 1 ) ).add( eq( sessionId ), anyInt(), any(), any( Transcoder.class ) );
verify( _memcachedMock, times( 1 ) ).add( eq( backupSessionKey ), anyInt(), any(), any( Transcoder.class ) );
verify( _memcachedMock, times( 1 ) ).set( eq( backupValidityKey ), eq( 0 ), any(), any( Transcoder.class ) );

代码示例来源:origin: io.snappydata/gemfire-junit

public void testFlushDelay() throws Exception {
 MemcachedClient client = bootstrapClient();
 Future<Boolean> b = client.flush(5);
 assertTrue(b.get());
 assertNotNull(client.get("key"));
 assertNotNull(client.get("key1"));
 Thread.sleep(8*1000);
 assertNull(client.get("key"));
 assertNull(client.get("key1"));
}

代码示例来源:origin: magro/memcached-session-manager

_service.backupSession( session.getIdInternal(), false, "foo" ).get();
verify( _memcachedMock, times( 1 ) ).delete( eq( oldSessionId ) );
verify( _memcachedMock, times( 1 ) ).set( eq( session.getId() ), anyInt(), any(), any( Transcoder.class ) );
  verify( _memcachedMock, times( 1 ) ).delete( eq( new SessionIdFormat().createValidityInfoKeyName( oldSessionId ) ) );
  verify( _memcachedMock, times( 1 ) ).set( eq( new SessionIdFormat().createValidityInfoKeyName( session.getId() ) ), anyInt(), any(), any( Transcoder.class ) );

代码示例来源:origin: magro/memcached-session-manager

/**
 * Test for issue #105: Make memcached node optional for single-node setup
 * http://code.google.com/p/memcached-session-manager/issues/detail?id=105
 */
@Test
public void testBackupSessionFailureWithoutMemcachedNodeIdConfigured105() throws Exception {
  _service.setMemcachedNodes( "127.0.0.1:11211" );
  _service.setSessionBackupAsync(false);
  _service.startInternal(new MemcachedStorageClient(_memcachedMock));
  final MemcachedBackupSession session = createSession( _service );
  session.access();
  session.endAccess();
  session.setAttribute( "foo", "bar" );
  @SuppressWarnings( "unchecked" )
  final OperationFuture<Boolean> futureMock = mock( OperationFuture.class );
  when( futureMock.get( ) ).thenThrow(new ExecutionException(new RuntimeException("Simulated exception.")));
  when( futureMock.get( anyInt(), any( TimeUnit.class ) ) ).thenThrow(new ExecutionException(new RuntimeException("Simulated exception.")));
  when( _memcachedMock.set(  eq( session.getId() ), anyInt(), any(), any( Transcoder.class ) ) ).thenReturn( futureMock );
  final BackupResult backupResult = _service.backupSession( session.getIdInternal(), false, null ).get();
  assertEquals(backupResult.getStatus(), BackupResultStatus.FAILURE);
  verify( _memcachedMock, times( 1 ) ).set( eq( session.getId() ), anyInt(), any(), any( Transcoder.class ) );
}

代码示例来源:origin: magro/memcached-session-manager

session.endAccess();
session.setAttribute( "foo", "bar" );
_service.backupSession( session.getIdInternal(), false, null ).get();
verify( _memcachedMock, times( 1 ) ).set( eq( session.getId() ), anyInt(), any(), any( Transcoder.class ) );
session.setAttribute( "foo", "bar" );
session.setAttribute( "bar", "baz" );
_service.backupSession( session.getIdInternal(), false, null ).get();
verify( _memcachedMock, times( 2 ) ).set( eq( session.getId() ), anyInt(), any(), any( Transcoder.class ) );
_service.backupSession( session.getIdInternal(), false, null ).get();
verify( _memcachedMock, times( 2 ) ).set( eq( session.getId() ), anyInt(), any(), any( Transcoder.class ) );

代码示例来源:origin: org.infinispan/infinispan-cli-interpreter

public void testMemcachedCodec() throws Exception {
 Cache<byte[], byte[]> cache = cacheManager.getCache(MEMCACHED_CACHE);
 memcachedClient.set("k1", 3600, "v1").get();
 assertTrue(cache.containsKey("k1".getBytes()));
 String sessionId = interpreter.createSessionId(MEMCACHED_CACHE);
 Map<String, String> response = interpreter.execute(sessionId, "get --codec=memcached k1;");
 assertEquals("v1", response.get(ResultKeys.OUTPUT.toString()));
 interpreter.execute(sessionId, "put --codec=memcached k2 v2;");
 String v2 = (String) memcachedClient.get("k2");
 assertEquals("v2", v2);
}

代码示例来源:origin: org.infinispan/infinispan-compatibility-mode-it

public void testEmbeddedPutMemcachedGet() throws IOException {
 // 1. Put with Embedded
 for (int i = 0; i != numEntries; i++) {
   assertEquals(null, cacheFactory2.getEmbeddedCache().put("k" + i, "v" + i));
 }
 // 2. Get with Memcached from a different node
 for (int i = 0; i != numEntries; i++) {
   assertEquals("v" + i, cacheFactory1.getMemcachedClient().get("k" + i));
 }
}

代码示例来源:origin: apache/hbase

@Override
public void shutdown() {
 client.shutdown();
}

代码示例来源:origin: ninjaframework/ninja

public void set(String key, Object value, int expiration) {
  client.set(key, expiration, value, tc);
}

相关文章