net.rubyeye.xmemcached.MemcachedClient Java Examples

The following examples show how to use net.rubyeye.xmemcached.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: 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 #2
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 #3
Source File: RoutingMemcacheClientFactoryImpl.java    From cloud-config with MIT License 6 votes vote down vote up
@Override
public CacheClient create(final List<InetSocketAddress> addrs, final CacheConfiguration conf) throws IOException {
    MemcacheClientWrapper clientWrapper = (MemcacheClientWrapper)super.create(addrs, conf);
    if (resolver==null) {
        return clientWrapper;
    }
    final MemcachedClient memcachedClient = (MemcachedClient) clientWrapper.getNativeClient();
    Object proxyInstance = Proxy.newProxyInstance( getClass().getClassLoader(), new Class[]{ MemcachedClient.class }, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(resolver.get().isPresent()) {
                String routingKey = resolver.get().get();
                memcachedClient.beginWithNamespace(routingKey);
                try {
                    return method.invoke(memcachedClient, args);
                } finally {
                    memcachedClient.endWithNamespace();
                }
            } else {
                throw new IllegalStateException("Unresolved routing key");
            }
        }
    });
    return new MemcacheClientWrapper((MemcachedClient) proxyInstance) ;
}
 
Example #4
Source File: MemcachedCacheMeterBinderProviderConfigurationTest.java    From memcached-spring-boot with Apache License 2.0 6 votes vote down vote up
@Bean
public MemcachedCacheManager cacheManager() {
    final IMemcachedClient memcachedClient = mock(IMemcachedClient.class);
    final MemcachedClient client = mock(MemcachedClient.class);


    given(memcachedClient.get(any()))
            .willReturn("namespace").willReturn(null)
            .willReturn("namespace").willReturn(null)
            .willReturn("namespace").willReturn("b")
            .willReturn("namespace").willReturn(null)
            .willReturn("namespace").willReturn(null)
            .willReturn("namespace").willReturn("c")
            .willReturn("namespace").willReturn("a")
            .willReturn("namespace").willReturn("a")
            .willReturn("namespace").willReturn("a")
            .willReturn("namespace").willReturn("d");
    given(memcachedClient.nativeCache()).willReturn(client);
    given(client.getAvailableServers())
            .willReturn(Collections.singletonList(new InetSocketAddress("127.0.0.1", 11222)));

    return new MemcachedCacheManager(memcachedClient);
}
 
Example #5
Source File: MemcachedAssertions.java    From memcached-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts {@link MemcachedClient} against expected configuration values.
 *
 * @param memcachedClient {@link MemcachedClient}
 * @param protocol        Expected protocol
 * @param servers         Expected server list
 */
public static void assertMemcachedClient(IMemcachedClient memcachedClient, MemcachedCacheProperties.Protocol protocol, long operationTimeout, InetSocketAddress... servers) {
    final MemcachedClient nativeCache = (MemcachedClient) memcachedClient.nativeCache();

    final MemcachedConnector connector = (MemcachedConnector) nativeCache.getConnector();
    final InetSocketAddress[] availableServers = nativeCache.getAvailableServers().toArray(new InetSocketAddress[]{});

    assertThat(nativeCache.getOpTimeout()).isEqualTo(operationTimeout);
    assertThat(connector.getProtocol().name().toUpperCase()).isEqualTo(protocol.name());

    final List<InetSocketAddress> actualServers = Arrays.asList(servers);

    if (actualServers.size() > 0) {
        assertThat(availableServers)
                .as("The number of memcached node endpoints should match server list size")
                .hasSize(servers.length);

        for (int i = 0; i < availableServers.length; i++) {
            InetSocketAddress address = availableServers[i];

            assertThat(actualServers).contains(address);
        }
    }
}
 
Example #6
Source File: MemcachedAssertions.java    From memcached-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts {@link MemcachedClient} against expected configuration values.
 *
 * @param memcachedClient {@link MemcachedClient}
 * @param protocol        Expected protocol
 * @param servers         Expected server list
 */
public static void assertMemcachedClient(IMemcachedClient memcachedClient, MemcachedCacheProperties.Protocol protocol, long operationTimeout, InetSocketAddress... servers) {
    final MemcachedClient nativeCache = (MemcachedClient) memcachedClient.nativeCache();

    final MemcachedConnector connector = (MemcachedConnector) nativeCache.getConnector();
    final InetSocketAddress[] availableServers = nativeCache.getAvailableServers().toArray(new InetSocketAddress[]{});

    assertThat(nativeCache.getOpTimeout()).isEqualTo(operationTimeout);
    assertThat(connector.getProtocol().name().toUpperCase()).isEqualTo(protocol.name());

    final List<InetSocketAddress> actualServers = Arrays.asList(servers);

    if (actualServers.size() > 0) {
        assertThat(availableServers)
                .as("The number of memcached node endpoints should match server list size")
                .hasSize(servers.length);

        for (int i = 0; i < availableServers.length; i++) {
            InetSocketAddress address = availableServers[i];

            assertThat(actualServers).contains(address);
        }
    }
}
 
Example #7
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 #8
Source File: XmemcachedFactoryTest.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() throws IOException {
    System.out.println("create");
    CommandFactory protocol = new BinaryCommandFactory();
    String user = "";
    String pass = "";
    String[] authMechanisms = new String[]{"PLAIN"};
    MemcachedClient result = XmemcachedFactory.create(HOST, protocol, user, pass, authMechanisms);
    assertNotNull(result);
    assertFalse(result.isShutdown());
    result.shutdown();
    assertTrue(result.isShutdown());
}
 
Example #9
Source File: XmemcachedFactoryTest.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_PippoSettings() throws IOException {
    System.out.println("create");
    MemcachedClient result = XmemcachedFactory.create(application.getPippoSettings());
    assertNotNull(result);
    assertFalse(result.isShutdown());
    result.shutdown();
    assertTrue(result.isShutdown());
}
 
Example #10
Source File: MemcachedPool.java    From jea with Apache License 2.0 5 votes vote down vote up
public ICacheCommands getResource() throws Exception {
	if(builder == null){
		initPool();
	}
	MemcachedClient client = builder.build();
	return new MemcachedCommands(client, socketAddress);
}
 
Example #11
Source File: MemcacheClientFactoryImpl.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
private void setProviderClientSpecificSettings(final MemcachedClient client, final XMemcachedConfiguration conf) {
    if (conf.getMaxAwayTime() != null) {
        client.addStateListener(new ReconnectListener(conf.getMaxAwayTime()));
    }

    if (conf.getEnableHeartBeat() != null) {
        client.setEnableHeartBeat(conf.getEnableHeartBeat());
    }

    if (conf.getHealSessionInterval() != null) {
        client.setHealSessionInterval(conf.getHealSessionInterval());
    }

    if (conf.getMergeFactor() != null) {
        client.setMergeFactor(conf.getMergeFactor());
    }

    if (conf.getOptimizeGet() != null) {
        client.setOptimizeGet(conf.getOptimizeGet());
    }

    if (conf.getOptimizeMergeBuffer() != null) {
        client.setOptimizeMergeBuffer(conf.getOptimizeMergeBuffer());
    }

    if (conf.getPrimitiveAsString() != null) {
        client.setPrimitiveAsString(conf.getPrimitiveAsString());
    }

    if (conf.getSanitizeKeys() != null) {
        client.setSanitizeKeys(conf.getSanitizeKeys());
    }

}
 
Example #12
Source File: SyncLockMapCache.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
public SyncLockMapCache(String name, MemcachedClient memcachedClient,
		LocalZookeeperLock lock) throws CacheException {
	if (StringUtils.isBlank(name))
		throw new CacheException("缓存key不允许为空.");
	this.name = name;
	this.memcachedClient = memcachedClient;
	this.lock = lock;
}
 
Example #13
Source File: MemCacheMapCache.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
public MemCacheMapCache(String name, MemcachedClient memcachedClient)
		throws CacheException {
	if (StringUtils.isBlank(name))
		throw new CacheException("缓存key不允许为空.");
	if (memcachedClient == null) {
		throw new CacheException("memcachedClient不允许为空.");
	}

	this.memcachedClient = memcachedClient;
	this.name = name;
}
 
Example #14
Source File: SpringContextHelper.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
	this.applicationContext = applicationContext;
	this.client = getBean("memcachedClient", MemcachedClient.class);
}
 
Example #15
Source File: MemcachedCacheTest.java    From memcached-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void whenGetNativeThenReturnMemcachedClient() {
    final MemcachedClient client = mock(MemcachedClient.class);
    when(memcachedClient.nativeCache()).thenReturn(client);

    MemcachedClient actual = (MemcachedClient) memcachedCache.getNativeCache();

    assertThat(actual).isSameAs(client);

    verify(memcachedClient).nativeCache();
}
 
Example #16
Source File: AuthenticationInfoUtil.java    From ChengFeng1.5 with MIT License 5 votes vote down vote up
public static com.beautifulsoup.chengfeng.pojo.User getUser(UserMapper userMapper, MemcachedClient memcachedClient) throws InterruptedException, MemcachedException, TimeoutException {
    User authenticationInfo = AuthenticationInfoUtil.getAuthenticationInfo();
    String userJson = memcachedClient.get(authenticationInfo.getUsername());
    com.beautifulsoup.chengfeng.pojo.User user;
    if (!StringUtils.isBlank(userJson)){
        user= JsonSerializableUtil.string2Obj(userJson, com.beautifulsoup.chengfeng.pojo.User.class);

    }else{
        user=userMapper.selectByNickname(authenticationInfo.getUsername());
    }
    return user;
}
 
Example #17
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 #18
Source File: SystemCacheManager.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
public SystemCacheManager(net.sf.ehcache.CacheManager cacheManager,MemcachedClient memcachedClient,
		SelectCache selectCache,MemcachedManager memcachedManager) {
	this.ehCacheManager = cacheManager;
	this.memcachedClient = memcachedClient;
	this.selectCache = selectCache;
	this.memcachedManager = memcachedManager;
}
 
Example #19
Source File: MemcachedCacheMetrics.java    From memcached-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
    if (cache.getNativeCache() instanceof MemcachedClient) {
        final MemcachedClient memcachedClient = (MemcachedClient) cache.getNativeCache();

        registry.gauge("available_servers_count", memcachedClient.getAvailableServers().size());
    }
}
 
Example #20
Source File: MemcacheCache.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Create an {@link EhCacheCache} instance.
 * @param ehcache backing Ehcache instance
 */
public MemcacheCache(MemcachedClient cache,MemcachedManager memcachedManager,String namespace,Integer expireTime) {
	Assert.notNull(cache, "Memcached不能为null");
//	Status status = ehcache.getStatus();
//	Assert.isTrue(Status.STATUS_ALIVE.equals(status),
//			"An 'alive' Ehcache is required - current cache is " + status.toString());
	this.cache = cache;
	this.memcachedManager = memcachedManager;
	this.namespace = namespace;
	this.expireTime = expireTime;
}
 
Example #21
Source File: SystemCacheManager.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setMemcachedClient(MemcachedClient memcachedClient) {
	this.memcachedClient = memcachedClient;
}
 
Example #22
Source File: MemCache.java    From J2Cache with Apache License 2.0 4 votes vote down vote up
public MemCache(String region, MemcachedClient client) {
    this.region = region;
    this.client = client;
}
 
Example #23
Source File: MemcachedCommands.java    From jea with Apache License 2.0 4 votes vote down vote up
public MemcachedCommands(MemcachedClient commands, List<InetSocketAddress> socketAddress){
	this.commands = commands;
	this.socketAddress = socketAddress;
}
 
Example #24
Source File: MemcacheClientWrapperTest.java    From simple-spring-memcached with MIT License 4 votes vote down vote up
private MemcachedClient getMock() {
    return EasyMock.createMock(MemcachedClient.class);
}
 
Example #25
Source File: MemcacheClientWrapper.java    From simple-spring-memcached with MIT License 4 votes vote down vote up
MemcacheClientWrapper(final MemcachedClient memcachedClient) {
    this.memcachedClient = memcachedClient;
}
 
Example #26
Source File: ReconnectListener.java    From simple-spring-memcached with MIT License 4 votes vote down vote up
@Override
public void onDisconnected(final MemcachedClient memcachedClient, final InetSocketAddress inetSocketAddress) {
    removedServers.put(inetSocketAddress, System.currentTimeMillis());
}
 
Example #27
Source File: SystemCacheManager.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
public MemcachedClient getMemcachedClient() {
	return memcachedClient;
}
 
Example #28
Source File: MemCacheManagerImpl.java    From MultimediaDesktop with Apache License 2.0 4 votes vote down vote up
public void setMemcachedClient(MemcachedClient memcachedClient) {
	this.memcachedClient = memcachedClient;
}
 
Example #29
Source File: XMemcachedClient.java    From memcached-spring-boot with Apache License 2.0 4 votes vote down vote up
public XMemcachedClient(MemcachedClient memcachedClient) {
    this.memcachedClient = memcachedClient;
}
 
Example #30
Source File: MemcachedManager.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setMemcachedClient(MemcachedClient memcachedClient) {
	this.memcachedClient = memcachedClient;
}