当前位置: 首页>>代码示例>>Java>>正文


Java MemcachedClient类代码示例

本文整理汇总了Java中net.spy.memcached.MemcachedClient的典型用法代码示例。如果您正苦于以下问题:Java MemcachedClient类的具体用法?Java MemcachedClient怎么用?Java MemcachedClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


MemcachedClient类属于net.spy.memcached包,在下文中一共展示了MemcachedClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: initMemcached

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
public void initMemcached(String addresses) // addresses: space sep. like 'localhost:11211 10.10.10.10:1234'
{
    if (memcachedClient.get() != null)
        throw new IllegalStateException("memcached already initialized");
    try
    {
        final MemcachedClient _memcachedClient = new MemcachedClient(
                new BinaryConnectionFactory(),
                AddrUtil.getAddresses(addresses));
        _memcachedClient.addObserver(this);
        memcachedClient.set(_memcachedClient);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
开发者ID:rtr-nettest,项目名称:open-rmbt,代码行数:18,代码来源:CacheHelper.java

示例2: MemCacheTicketRegistry

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
/**
 * Creates a new instance that stores tickets in the given memcached hosts.
 *
 * @param hostnames                   Array of memcached hosts where each element is of the form host:port.
 * @param ticketGrantingTicketTimeOut TGT timeout in seconds.
 * @param serviceTicketTimeOut        ST timeout in seconds.
 */
@Autowired
public MemCacheTicketRegistry(@Value("${memcached.servers:}")
                              final String[] hostnames,
                              @Value("${tgt.maxTimeToLiveInSeconds:28800}")
                              final int ticketGrantingTicketTimeOut,
                              @Value("${st.timeToKillInSeconds:10}")
                              final int serviceTicketTimeOut) {

    try {
        final List<String> hostNamesArray = Arrays.asList(hostnames);
        if (hostNamesArray.isEmpty()) {
            logger.debug("No memcached hosts are define. Client shall not be configured");
        } else {
            logger.info("Setting up Memcached Ticket Registry...");
            this.tgtTimeout = ticketGrantingTicketTimeOut;
            this.stTimeout = serviceTicketTimeOut;

            this.client = new MemcachedClient(AddrUtil.getAddresses(hostNamesArray));
        }
    } catch (final IOException e) {
        throw new IllegalArgumentException("Invalid memcached host specification.", e);
    }

}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:32,代码来源:MemCacheTicketRegistry.java

示例3: main

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
public static void main(String[] args) {

   try{

      // 连接本地的 Memcached 服务
      MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("172.18.3.34", 9101));
      System.out.println("Connection to server sucessful.");

      // 添加数据
      Future fo = mcc.set("runoob", 900, "Free Education");

      // 输出执行 set 方法后的状态
      System.out.println("set status:" + fo.get());

      // 使用 get 方法获取数据
      System.out.println("runoob value in cache - " + mcc.get("runoob"));

      // 关闭连接
      mcc.shutdown();
      
   }catch(Exception ex) {
      System.out.println(ex.getMessage());
      }
}
 
开发者ID:alamby,项目名称:upgradeToy,代码行数:25,代码来源:MemcachedJava.java

示例4: testGemFireProperty

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
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();
}
 
开发者ID:gemxd,项目名称:gemfirexd-oss,代码行数:20,代码来源:IntegrationJUnitTest.java

示例5: whenCacheManagerBeanAlreadyInContextThenMemcachedWithNonCustomConfigurationLoaded

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Test
public void whenCacheManagerBeanAlreadyInContextThenMemcachedWithNonCustomConfigurationLoaded() {
    // add cache manager to the context before triggering auto-configuration on context load
    ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
    constructorArgumentValues.addGenericArgumentValue(mock(MemcachedClient.class));
    RootBeanDefinition cacheManagerBeanDefinition = new RootBeanDefinition(
            MemcachedCacheManager.class,
            constructorArgumentValues,
            null);
    applicationContext.registerBeanDefinition("cacheManager", cacheManagerBeanDefinition);

    loadContext(CacheConfiguration.class, "memcached.cache.expiration=3600",
            "memcached.cache.prefix=custom:prefix",
            "memcached.cache.namespace=custom_namespace");

    MemcachedCacheManager memcachedCacheManager = this.applicationContext.getBean(MemcachedCacheManager.class);

    assertThat(memcachedCacheManager)
            .as("Auto-configured disposable instance should not be loaded in context")
            .isNotInstanceOf(MemcachedCacheAutoConfiguration.DisposableMemcachedCacheManager.class);
    assertMemcachedCacheManager(memcachedCacheManager, Default.EXPIRATION, Default.PREFIX, Default.NAMESPACE);
}
 
开发者ID:sixhours-team,项目名称:memcached-spring-boot,代码行数:23,代码来源:MemcachedAutoConfigurationTest.java

示例6: memcachedClient

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Bean
public MemcachedClient memcachedClient(ObjectProvider<ConnectionFactory> connection) throws IOException {
    final List<InetSocketAddress> addresses = new ArrayList<>();
    final String servers = environment.getProperty("memcached.servers");
    if (StringUtils.isEmpty(servers)) {
        addresses.add(new InetSocketAddress(LOCALHOST, DEFAULT_PORT));
    } else {
        for (final String server : servers.split(",")) {
            final int colon = server.indexOf(":");
            if (colon == -1) {
                addresses.add(new InetSocketAddress(server, DEFAULT_PORT));
            } else {
                final int port = Integer.parseInt(server.substring(colon + 1));
                addresses.add(new InetSocketAddress(server.substring(0, colon), port));
            }
        }
    }

    ConnectionFactory con = connection.getIfUnique();

    return con == null
            ? new MemcachedClient(addresses)
            : new MemcachedClient(con, addresses);
}
 
开发者ID:bmatthews68,项目名称:memcached-spring-boot-starter,代码行数:25,代码来源:MemcachedAutoConfiguration.java

示例7: MemcachedDistributedGroup

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
/**
 * 构造memcached组
 * 
 * @param groupServerUrl
 *            -- 组中Memcached服务器连接字符串
 */
MemcachedDistributedGroup(String groupServerUrl) {
	this.groupServerUrl = groupServerUrl;
	String items = groupServerUrl.replaceAll(";", " ");
	try {
		mcc = new MemcachedClient(new DefaultConnectionFactory() {
			@Override
			public long getOperationTimeout() {
				return connectTimeout;
			}
		}, AddrUtil.getAddresses(items));

		initMemCachedHealthMBean(groupServerUrl);
	} catch (Exception ex) {
		throw new FwRuntimeException("初始化MemcachedClient对象失败", ex);
	}

}
 
开发者ID:bignippleboy,项目名称:ipaas,代码行数:24,代码来源:FwSpyDirectMemcachedService.java

示例8: ExceptionSwallowingMemcachedClient

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@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);
}
 
开发者ID:SeldonIO,项目名称:seldon-server,代码行数:23,代码来源:ExceptionSwallowingMemcachedClient.java

示例9: gets

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
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;
}
 
开发者ID:SeldonIO,项目名称:seldon-server,代码行数:19,代码来源:MemCachePeer.java

示例10: sendSpyMemcached

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
private static void sendSpyMemcached(final MemcachedClient client,
                                     final List<String> keys,
                                     final Map<String, String> expectedMap,
                                     final ProgressMeter meter,
                                     final ScheduledExecutorService backoffExecutor) {
  final long start = System.nanoTime();
  final BulkFuture<Map<String, Object>> future = client.asyncGetBulk(keys);
  future.addListener(getFuture -> {
    final OperationStatus status = getFuture.getStatus();
    if (status.isSuccess()) {
      final Map<String, String> response = (Map<String, String>) getFuture.get();
      final long end = System.nanoTime();
      final long latency = end - start;
      meter.inc(keys.size(), latency);
      if (!expectedMap.equals(response)) {
        throw new AssertionError("expected: " + expectedMap + ", got: " + response);
      }
      sendSpyMemcached(client, keys, expectedMap, meter, backoffExecutor);
    } else {
      System.err.println("failure!");
    }
  });
}
 
开发者ID:spotify,项目名称:folsom,代码行数:24,代码来源:SimpleMemcacheClientBenchmark.java

示例11: setInternal

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Override
protected void setInternal(final MemcachedClient mc, final String path,
    final List<INode> inodes) {
  if (INode.getPathNames(path).length != inodes.size()) {
    return;
  }
  final String key = getKey(path);
  final int[] inodeIds = getINodeIds(inodes);
  final long startTime = System.currentTimeMillis();
  mc.set(key, keyExpiry, new CacheEntry(inodeIds))
      .addListener(new OperationCompletionListener() {
        @Override
        public void onComplete(OperationFuture<?> f) throws Exception {
          long elapsed = System.currentTimeMillis() - startTime;
          LOG.debug("SET for path (" + path + ")  " + key + "=" +
              Arrays.toString(inodeIds) + " in " + elapsed + " msec");
        }
      });
}
 
开发者ID:hopshadoop,项目名称:hops,代码行数:20,代码来源:PathMemcache.java

示例12: getInternal

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Override
protected int[] getInternal(final MemcachedClient mc, String path) throws
    IOException {
  Object ce = null;
  Future<Object> f = mc.asyncGet(getKey(path));
  try {
    ce = f.get(1, TimeUnit.SECONDS);
  } catch (Exception ex) {
    LOG.error(ex);
    f.cancel(true);
  }
  if (ce != null && ce instanceof CacheEntry) {
    return ((CacheEntry) ce).getInodeIds();
  }
  return null;
}
 
开发者ID:hopshadoop,项目名称:hops,代码行数:17,代码来源:PathMemcache.java

示例13: getInternal

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Override
protected int[] getInternal(MemcachedClient mc, String path) throws
    IOException {
  String[] pathComponents = INode.getPathNames(path);
  int[] inodeIds = new int[pathComponents.length];
  int parentId = INodeDirectory.ROOT_PARENT_ID;
  int index = 0;
  while(index <pathComponents.length){
    String cmp = pathComponents[index];
    Integer inodeId = getInternal(mc, cmp, parentId);
    if(inodeId != null){
      parentId = inodeId;
      inodeIds[index] = inodeId;
    }else{
      break;
    }
    index++;
  }

  //only the root was found
  if(index <= 1)
    return null;

  return Arrays.copyOf(inodeIds, index);
}
 
开发者ID:hopshadoop,项目名称:hops,代码行数:26,代码来源:INodeMemcache.java

示例14: setInternal

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Override
protected void setInternal(MemcachedClient mc, String path,
    List<INode> inodes) {
  if(INode.getPathNames(path).length  != inodes.size())
    return;

  int lastIndex = path.lastIndexOf(Path.SEPARATOR);
  if(lastIndex <= 0)
    return;

  INode file = inodes.get(inodes.size() - 1);
  if(file.isDirectory()){
    super.setInternal(mc, path, inodes);
    return;
  }

  String parentPath = path.substring(0, lastIndex);
  super.setInternal(mc, parentPath, inodes.subList(0, inodes.size() - 1));
  setInternal(mc, file);
}
 
开发者ID:hopshadoop,项目名称:hops,代码行数:21,代码来源:OptimalMemcache.java

示例15: getInternal

import net.spy.memcached.MemcachedClient; //导入依赖的package包/类
@Override
protected int[] getInternal(MemcachedClient mc, String path)
    throws IOException {
  int lastIndex = path.lastIndexOf(Path.SEPARATOR);
  if(lastIndex <= 0)
    return null;

  String parentPath = path.substring(0, lastIndex);
  int[] inodeIds = super.getInternal(mc, parentPath);
  if(inodeIds == null)
    return null;

  String file = path.substring(lastIndex + 1, path.length());
  int fileParentId = inodeIds[inodeIds.length - 1];
  Integer fileInodeId = INodeMemcache.getInternal(mc, keyPrefix, file,
      fileParentId);
  if(fileInodeId != null){
    inodeIds = Arrays.copyOf(inodeIds, inodeIds.length + 1);
    inodeIds[inodeIds.length - 1] = fileInodeId;
  }
  return inodeIds;
}
 
开发者ID:hopshadoop,项目名称:hops,代码行数:23,代码来源:OptimalMemcache.java


注:本文中的net.spy.memcached.MemcachedClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。