net.rubyeye.xmemcached.utils.AddrUtil Java Examples

The following examples show how to use net.rubyeye.xmemcached.utils.AddrUtil. 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: TestFqueueServer.java    From fqueue with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {
    Config.setSetting("port", "12001");
    Config.setSetting("path", "dbtest");
    Config.setSetting("logsize", "40");
    Config.setSetting("authorization", "key|abc@@bbs|pass");
    StartNewQueue.newQueueInstance(Integer.parseInt(Config.getSetting("port")));
    log.info("running at port " + Config.getSetting("port"));
    builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("127.0.0.1:12001"));
    builder.setConnectionPoolSize(50); // set connection pool size to five

    try {
        client = builder.build();
        client.setOptimizeGet(false);
        builder.setSocketOption(StandardSocketOption.SO_KEEPALIVE, true);
        builder.setSocketOption(StandardSocketOption.SO_RCVBUF, 64 * 1024);
        builder.setSocketOption(StandardSocketOption.SO_SNDBUF, 64 * 1024);
        builder.setSocketOption(StandardSocketOption.SO_REUSEADDR, true);
        builder.setSocketOption(StandardSocketOption.TCP_NODELAY, false);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    client.get("clear|key|abc");
}
 
Example #2
Source File: TestFqueueServer.java    From fqueue with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {
    Config.setSetting("port", "12001");
    Config.setSetting("path", "dbtest");
    Config.setSetting("logsize", "40");
    Config.setSetting("authorization", "key|abc@@bbs|pass");
    StartNewQueue.newQueueInstance(Integer.parseInt(Config.getSetting("port")));
    log.info("running at port " + Config.getSetting("port"));
    builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("127.0.0.1:12001"));
    builder.setConnectionPoolSize(50); // set connection pool size to five

    try {
        client = builder.build();
        client.setOptimizeGet(false);
        builder.setSocketOption(StandardSocketOption.SO_KEEPALIVE, true);
        builder.setSocketOption(StandardSocketOption.SO_RCVBUF, 64 * 1024);
        builder.setSocketOption(StandardSocketOption.SO_SNDBUF, 64 * 1024);
        builder.setSocketOption(StandardSocketOption.SO_REUSEADDR, true);
        builder.setSocketOption(StandardSocketOption.TCP_NODELAY, false);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    client.get("clear|key|abc");
}
 
Example #3
Source File: MemcacheServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
    ServletException {
  String addr =
      System.getenv().containsKey("GAE_MEMCACHE_HOST")
          ? System.getenv("GAE_MEMCACHE_HOST") : "localhost";
  String port =
      System.getenv().containsKey("GAE_MEMCACHE_HOST")
          ? System.getenv("GAE_MEMCACHE_PORT") : "11211";
  String key = "count";
  MemcachedClientBuilder builder = new XMemcachedClientBuilder(
      AddrUtil.getAddresses(addr + ":" + port));
  MemcachedClient client = builder.build();
  long count = 0L;
  try {
    count = client.incr(key, 1L, 0L);
  } catch (TimeoutException | InterruptedException | MemcachedException e) {
    throw new ServletException("Memcache error", e);
  }
  resp.setContentType("text/plain");
  resp.getWriter().print("Value is " + count + "\n");
}
 
Example #4
Source File: MemcachedPool.java    From jea with Apache License 2.0 6 votes vote down vote up
/**
 * 分布策略为一致性哈希
 */
private void initPool(){
	StringBuffer memcachedAddr = new StringBuffer();
	for(String addr : addresses){
		memcachedAddr.append(addr).append(" ");
	}
	socketAddress = AddrUtil.getAddresses (memcachedAddr.toString().trim());
	builder = new XMemcachedClientBuilder(socketAddress);
	builder.setConnectionPoolSize(poolConfig.getMaxTotal());
	builder.setConnectTimeout(poolConfig.getMaxConnectMillis());
	builder.setFailureMode(poolConfig.getFailureMode());
	builder.setOpTimeout(poolConfig.getMaxWaitMillis());
	builder.setEnableHealSession(poolConfig.getEnableHealSession());
	builder.setHealSessionInterval(poolConfig.getHealSessionInterval());
	/**
	 * 分布策略
	 * 默认分布的策略是按照key的哈希值模以连接数得到的余数
	 * KetamaMemcachedSessionLocator:一致性哈希(consistent hash)
	 * ElectionMemcachedSessionLocator:选举散列哈希算法
	 */
	builder.setSessionLocator(new KetamaMemcachedSessionLocator());
}
 
Example #5
Source File: XmemcachedFactory.java    From pippo with Apache License 2.0 6 votes vote down vote up
/**
 * Create a memcached client with params.
 *
 * @param hosts whitespace separated host or IP addresses and port numbers
 * of the form "host:port host2:port hostN:portN"
 * @param protocol opcional, BINARY or TEXT
 * @param user opcional, user name o null
 * @param pass opcional, password o null
 * @param authMechanisms opcional, CRAM-MD5 and/or PLAIN
 * @return memcached client
 */
public static MemcachedClient create(
        String hosts,
        CommandFactory protocol,
        String user,
        String pass,
        String[] authMechanisms) {
    MemcachedClient client = null;
    try {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(hosts));
        builder.setCommandFactory(protocol);
        if (isNotNullOrEmpty(user)) {
            builder.addAuthInfo(
                    AddrUtil.getAddresses(hosts).get(0),
                    new AuthInfo(
                            new PlainCallbackHandler(user, pass),
                            authMechanisms));
        }
        client = builder.build();
    } catch (IOException ex) {
        log.error("An error occurred when creating the MemcachedClient.", ex);
        throw new PippoRuntimeException(ex);
    }
    return client;
}
 
Example #6
Source File: MemcachedConfig.java    From ChengFeng1.5 with MIT License 5 votes vote down vote up
@Bean
public MemcachedClient getMemcachedClient() {
    MemcachedClient memcachedClient = null;
    try {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.
                getAddresses(memcachedProperties.getServers()));
        builder.setConnectionPoolSize(memcachedProperties.getPoolSize());
        builder.setOpTimeout(memcachedProperties.getOpTimeout());
        memcachedClient = builder.build();
    } catch (IOException e) {
        log.error("inint MemcachedClient failed ",e);
    }
    return memcachedClient;
}
 
Example #7
Source File: XmemcachedCacheProvider.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Properties props) {

    long ct = System.currentTimeMillis();

    String servers = props.getProperty("servers", "127.0.0.1:11211");
    String username = props.getProperty("username", "");
    String password = props.getProperty("password", "");
    MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(servers));
    builder.setCommandFactory(new BinaryCommandFactory());
    boolean needAuth = username != null && password != null && username.trim().length() > 0 && password.trim().length() > 0;
    if(needAuth)
        builder.addAuthInfo(AddrUtil.getOneAddress(servers), AuthInfo.typical(username, password));

    builder.setConnectionPoolSize(Integer.valueOf(props.getProperty("connectionPoolSize", "10")));
    builder.setConnectTimeout(Long.valueOf(props.getProperty("connectTimeout", "1000")));
    builder.setHealSessionInterval(Long.valueOf(props.getProperty("healSessionInterval", "1000")));
    builder.setMaxQueuedNoReplyOperations(Integer.valueOf(props.getProperty("maxQueuedNoReplyOperations", "100")));
    builder.setOpTimeout(Long.valueOf(props.getProperty("opTimeout", "100")));
    builder.setSanitizeKeys("true".equalsIgnoreCase(props.getProperty("sanitizeKeys", "false")));

    try {
        client = builder.build();

        log.info("Memcached client starts with servers({}),auth({}),pool-size({}),time({}ms)",
                servers,
                needAuth,
                builder.getConfiguration().getSelectorPoolSize(),
                System.currentTimeMillis() - ct
        );
    } catch (IOException e) {
        log.error("Failed to connect to memcached", e);
    }
}
 
Example #8
Source File: MemcachedConfig.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
@Bean
public MemcachedClient memcachedClient() throws IOException {
    MemcachedClientBuilder builder =
            new XMemcachedClientBuilder(AddrUtil.
                    getAddresses(address), new int[]{1});
    //存储的数据使用JSON格式,兼容不同客户端,如果是单一客户端可以不需要
    Transcoder JSON_TRANSCODER = new JSONTranscoder();
    builder.setTranscoder(JSON_TRANSCODER);

    return builder.build();
}
 
Example #9
Source File: XMemCached.java    From PeonyFramwork with Apache License 2.0 4 votes vote down vote up
@Override
public void init() {
	if (mcc != null)
		return;
	log.info("初始化XMemCached,ip:{},readBufSize:{},connectionPoolSize:{}",serverlist,readBufSize,connectionPoolSize);


	try {
		Configuration.MAX_READ_BUFFER_SIZE = Configuration.MAX_READ_BUFFER_SIZE * 2;

		List<InetSocketAddress> socketAddress = AddrUtil
				.getAddresses(serverlist);
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				socketAddress);
		builder.setConnectionPoolSize(connectionPoolSize);
		builder.setSocketOption(StandardSocketOption.TCP_NODELAY,
				tcpNoDelay);
		builder
				.setSocketOption(StandardSocketOption.SO_RCVBUF,
						tcpRecvBuff);
		builder
				.setSocketOption(StandardSocketOption.SO_SNDBUF,
						tcpSendBuff);
		if (this.transcoder == null) {
			this.transcoder = new SerializingTranscoder(10 * 1024 * 1024);// //最大单个数据大小:20M
		}
		builder.setTranscoder(transcoder);
		builder.getConfiguration()
				.setSessionIdleTimeout(sessionIdleTimeout);
		mcc = builder.build();
		mcc.setOpTimeout(this.opTimeout);
		//
		Field shutdownHookThread = null;
		try {
			shutdownHookThread = mcc.getClass().getDeclaredField(
					"shutdownHookThread");
			if (shutdownHookThread != null) {
				shutdownHookThread.setAccessible(true);
				Thread thread = (Thread) shutdownHookThread.get(mcc);
				// shutdownHookThread.set
				if (thread != null) {
					Runtime.getRuntime().removeShutdownHook(thread);
					log.info("删除XMemcached的shutDownHook!");
				}
				thread = new Thread() {
					@Override
					public void run() {
						log.info("修改过的xMemcached shutdown thread,什么也不做....");
						// TDOD 关闭的时候清空memecache,后面要改过来
						
					}
				};
				shutdownHookThread.set(mcc, thread);
				Runtime.getRuntime().addShutdownHook(thread);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		log.info("初始化  memcached client 完毕!");
	} catch (Exception ex) {
		log.debug("初始化  memcached client 出错!");
		log.error(ex.getMessage());
	}

}