Search in sources :

Example 1 with XMemcachedClientBuilder

use of net.rubyeye.xmemcached.XMemcachedClientBuilder in project java-docs-samples by GoogleCloudPlatform.

the class MemcacheServlet method doGet.

@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");
}
Also used : ServletException(javax.servlet.ServletException) XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) MemcachedClientBuilder(net.rubyeye.xmemcached.MemcachedClientBuilder) MemcachedClient(net.rubyeye.xmemcached.MemcachedClient) XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) TimeoutException(java.util.concurrent.TimeoutException) MemcachedException(net.rubyeye.xmemcached.exception.MemcachedException)

Example 2 with XMemcachedClientBuilder

use of net.rubyeye.xmemcached.XMemcachedClientBuilder in project dubbo by alibaba.

the class MemcachedProtocol method protocolBindingRefer.

@Override
public <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException {
    try {
        String address = url.getAddress();
        String backup = url.getParameter(RemotingConstants.BACKUP_KEY);
        if (backup != null && backup.length() > 0) {
            address += "," + backup;
        }
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(address));
        final MemcachedClient memcachedClient = builder.build();
        final int expiry = url.getParameter("expiry", 0);
        final String get = url.getParameter("get", "get");
        final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {

            @Override
            protected Result doInvoke(Invocation invocation) throws Throwable {
                try {
                    Object value = null;
                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The memcached get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        value = memcachedClient.get(String.valueOf(invocation.getArguments()[0]));
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException("The memcached set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        memcachedClient.set(String.valueOf(invocation.getArguments()[0]), expiry, invocation.getArguments()[1]);
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The memcached delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        memcachedClient.delete(String.valueOf(invocation.getArguments()[0]));
                    } else {
                        throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in memcached service.");
                    }
                    return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke memcached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t);
                    if (t instanceof TimeoutException || t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof MemcachedException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    }
                    throw re;
                }
            }

            @Override
            public void destroy() {
                super.destroy();
                try {
                    memcachedClient.shutdown();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer memcached service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t);
    }
}
Also used : XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) MemcachedClientBuilder(net.rubyeye.xmemcached.MemcachedClientBuilder) Invocation(org.apache.dubbo.rpc.Invocation) AbstractInvoker(org.apache.dubbo.rpc.protocol.AbstractInvoker) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) MemcachedClient(net.rubyeye.xmemcached.MemcachedClient) RpcException(org.apache.dubbo.rpc.RpcException) XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) MemcachedException(net.rubyeye.xmemcached.exception.MemcachedException)

Example 3 with XMemcachedClientBuilder

use of net.rubyeye.xmemcached.XMemcachedClientBuilder in project dubbo by alibaba.

the class MemcachedProtocol method refer.

public <T> Invoker<T> refer(final Class<T> type, final URL url) throws RpcException {
    try {
        String address = url.getAddress();
        String backup = url.getParameter(Constants.BACKUP_KEY);
        if (backup != null && backup.length() > 0) {
            address += "," + backup;
        }
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(address));
        final MemcachedClient memcachedClient = builder.build();
        final int expiry = url.getParameter("expiry", 0);
        final String get = url.getParameter("get", "get");
        final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set");
        final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete");
        return new AbstractInvoker<T>(type, url) {

            protected Result doInvoke(Invocation invocation) throws Throwable {
                try {
                    if (get.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The memcached get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        return new RpcResult(memcachedClient.get(String.valueOf(invocation.getArguments()[0])));
                    } else if (set.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 2) {
                            throw new IllegalArgumentException("The memcached set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        memcachedClient.set(String.valueOf(invocation.getArguments()[0]), expiry, invocation.getArguments()[1]);
                        return new RpcResult();
                    } else if (delete.equals(invocation.getMethodName())) {
                        if (invocation.getArguments().length != 1) {
                            throw new IllegalArgumentException("The memcached delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url);
                        }
                        memcachedClient.delete(String.valueOf(invocation.getArguments()[0]));
                        return new RpcResult();
                    } else {
                        throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in memcached service.");
                    }
                } catch (Throwable t) {
                    RpcException re = new RpcException("Failed to invoke memcached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t);
                    if (t instanceof TimeoutException || t instanceof SocketTimeoutException) {
                        re.setCode(RpcException.TIMEOUT_EXCEPTION);
                    } else if (t instanceof MemcachedException || t instanceof IOException) {
                        re.setCode(RpcException.NETWORK_EXCEPTION);
                    }
                    throw re;
                }
            }

            public void destroy() {
                super.destroy();
                try {
                    memcachedClient.shutdown();
                } catch (Throwable e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        };
    } catch (Throwable t) {
        throw new RpcException("Failed to refer memcached service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t);
    }
}
Also used : XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) MemcachedClientBuilder(net.rubyeye.xmemcached.MemcachedClientBuilder) Invocation(com.alibaba.dubbo.rpc.Invocation) RpcResult(com.alibaba.dubbo.rpc.RpcResult) AbstractInvoker(com.alibaba.dubbo.rpc.protocol.AbstractInvoker) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) MemcachedClient(net.rubyeye.xmemcached.MemcachedClient) RpcException(com.alibaba.dubbo.rpc.RpcException) XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) MemcachedException(net.rubyeye.xmemcached.exception.MemcachedException)

Example 4 with XMemcachedClientBuilder

use of net.rubyeye.xmemcached.XMemcachedClientBuilder in project SistemasDistribuidos by selatotal.

the class TesteMemcached method main.

public static void main(String[] args) {
    // Inicializa uma conexao com o Memcached
    XMemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));
    try {
        // Cria um cliente Memcached
        MemcachedClient client = builder.build();
        String nome = client.get("chaveNome");
        if (nome == null) {
            System.out.println("Chave nao encontrada no cache. Adicionando...");
            client.set("chaveNome", 0, "Tales Viegas");
        } else {
            System.out.println("Chave encontrada no cache: " + nome);
            System.out.println("Vou atualizar a chave!");
            client.set("chaveNome", 0, "John Doe");
        }
        // Exemplo JSON
        Gson gson = new Gson();
        String json = "{ " + "    \"servers\": [" + "        {" + "            \"name\": \"serverTales\"," + "            \"location\": \"999.999.999.999:9999\"," + "            \"sectors\": [" + "                {" + "                	\"code\" : 1," + "                	\"description\" : \"setor 1\"" + "                }," + "                {" + "                	\"code\" : 2," + "                	\"description\" : \"setor 2\"" + "                }," + "                {" + "                	\"code\" : 3," + "                	\"description\" : \"setor 3\"" + "                }" + "            ]," + "            \"active\": true" + "        }," + "        {" + "            \"name\": \"serverViegas\"," + "            \"location\": \"999.999.999.999:9999\"," + "            \"sectors\": [" + "                {" + "                	\"code\" : 1," + "                	\"description\" : \"setor 1\"" + "                }," + "                {" + "                	\"code\" : 2," + "                	\"description\" : \"setor 2\"" + "                }," + "                {" + "                	\"code\" : 3," + "                	\"description\" : \"setor 3\"" + "                }" + "            ]," + "			\"active\": false" + "        }" + "    ]" + "}";
        // Converte um JSON para um objeto (no caso um ListServersModel)
        ListServersModel model = gson.fromJson(json, ListServersModel.class);
        // Converte um Objeto para um JSON
        json = gson.toJson(model);
        // adiciona o JSON no Memcached
        client.set("SD_ListServers", 0, gson.toJson(model));
        // Busca o JSON do Memcached
        json = client.get("SD_ListServers");
        model = gson.fromJson(json, ListServersModel.class);
        // Atualiza o objeto
        model.servers.get(0).active = !model.servers.get(0).active;
        // Salva novamente no Memcached
        json = gson.toJson(model);
        client.set("SD_ListServers", 0, gson.toJson(model));
        client.shutdown();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (MemcachedException e) {
        e.printStackTrace();
    }
}
Also used : XMemcachedClient(net.rubyeye.xmemcached.XMemcachedClient) MemcachedClient(net.rubyeye.xmemcached.MemcachedClient) XMemcachedClientBuilder(net.rubyeye.xmemcached.XMemcachedClientBuilder) Gson(com.google.gson.Gson) IOException(java.io.IOException) TimeoutException(java.util.concurrent.TimeoutException) MemcachedException(net.rubyeye.xmemcached.exception.MemcachedException)

Aggregations

TimeoutException (java.util.concurrent.TimeoutException)4 MemcachedClient (net.rubyeye.xmemcached.MemcachedClient)4 XMemcachedClientBuilder (net.rubyeye.xmemcached.XMemcachedClientBuilder)4 MemcachedException (net.rubyeye.xmemcached.exception.MemcachedException)4 IOException (java.io.IOException)3 MemcachedClientBuilder (net.rubyeye.xmemcached.MemcachedClientBuilder)3 SocketTimeoutException (java.net.SocketTimeoutException)2 Invocation (com.alibaba.dubbo.rpc.Invocation)1 RpcException (com.alibaba.dubbo.rpc.RpcException)1 RpcResult (com.alibaba.dubbo.rpc.RpcResult)1 AbstractInvoker (com.alibaba.dubbo.rpc.protocol.AbstractInvoker)1 Gson (com.google.gson.Gson)1 ServletException (javax.servlet.ServletException)1 XMemcachedClient (net.rubyeye.xmemcached.XMemcachedClient)1 Invocation (org.apache.dubbo.rpc.Invocation)1 RpcException (org.apache.dubbo.rpc.RpcException)1 AbstractInvoker (org.apache.dubbo.rpc.protocol.AbstractInvoker)1