Memcache的客户端连接系列(一) Java

声明:本文并非原创,转自华为云帮助中心的分布式缓存服务(Memcached)的用户指南。

关键词: Memcached  客户端 Java Java连接池

Java客户端示例

  • 用户的弹性云服务器已安装好Java JDK和常用的IDE(如Eclipse)。
  • 已获取spymemcached-x.y.z.jar依赖包。
     说明:

    其中x.y.z为依赖包的版本号,建议获取最新版本。

  1. 获取缓存实例的IP和端口。
    1. 登录管理控制台
    2. 在管理控制台左上角单击图标,选择区域和项目。
       说明:

      此处请选择与租户的应用服务相同的区域。

    3. 单击页面上方的“服务列表”,选择“数据库 > 分布式缓存服务”,进入分布式缓存服务信息页面。
    4. 单击左侧菜单栏的“缓存管理”,进入缓存实例信息页面。
    5. 单击需要使用的其中一个缓存实例的名称,进入该缓存实例的基本信息页面。查看并获取该分布式缓存实例的IP地址/域名和端口。
  2. 将已获取的spymemcached-x.y.z.jar依赖包上传到已创建的弹性云服务器。
  3. 登录弹性云服务器。
  4. 创建Eclipse Project并将spymemcached-x.y.z.jar依赖包导入。
  5. 将如下Java代码复制到Eclipse Project中并修改代码。
    • 密码模式代码示例

      其中ip or domain name:port需要修改为1获取的缓存实例IP地址/域名和端口。userName和password需要修改为缓存实例的用户名和密码。

    //java 连接加密的Memcached代码
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    import net.spy.memcached.AddrUtil;
    import net.spy.memcached.ConnectionFactoryBuilder;
    import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
    import net.spy.memcached.MemcachedClient;
    import net.spy.memcached.auth.AuthDescriptor;
    import net.spy.memcached.auth.PlainCallbackHandler;
    import net.spy.memcached.internal.OperationFuture;
    
    public class ConnectMemcached1
    {
        public static void main(String[] args)
        {
            final String connectionaddress = "ip or domain name:port";//"ip or domain name:port"
            final String username = "userName";//用户名
            final String password = "password";//密码
            MemcachedClient client = null;
            try
            {
                AuthDescriptor authDescriptor =
                    new AuthDescriptor(new String[] {"PLAIN"}, new PlainCallbackHandler(username,
                            password));
                client = new MemcachedClient(
                        new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
                                .setAuthDescriptor(authDescriptor)
                                .build(),
                        AddrUtil.getAddresses(connectionaddress));
                String key = "memcached";//向Memcached中存一个key为"memcached"的数据
                String value = "Hello World";//value为Hello World
                int expireTime = 5; // 过期时间,单位s; 从写入时刻开始计时,超过expireTime s后,该数据过期失效,无法再读出;
                doExcute(client, key, value, expireTime);//执行操作
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    
        /**
         *向Memcached写数据方法
         */
        private static void doExcute(MemcachedClient client, String key, String value, int expireTime)
        {
            try
            {
                OperationFuture<Boolean> future = client.set(key, expireTime, value);
                future.get();// spymemcached set()是异步的,future.get() 等待cache.set()操作结束,也可以不等待,用户根据自己需求选择;
                System.out.println("Set操作成功");
                System.out.println("Get操作:" + client.get(key));
                Thread.sleep(6000);//等待6000毫秒,即6秒,该数据将会过期失效,无法再读出
                System.out.println("6秒后再执行Get操作:" + client.get(key));
    
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            catch (ExecutionException e)
            {
                e.printStackTrace();
            }
            if (client != null)
            {
                client.shutdown();
            }
        }
    }
    
     
    • 免密模式代码示例

      其中ip or domain name:port需要修改为1获取的缓存实例IP地址/域名和端口。

    //java 连接免密的Memcached代码
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    import net.spy.memcached.AddrUtil;
    import net.spy.memcached.BinaryConnectionFactory;
    import net.spy.memcached.MemcachedClient;
    import net.spy.memcached.internal.OperationFuture;
    
    public class ConnectMemcached
    {
        public static void main(String[] args)
        {
            final String connectionaddress = "ip or domain name:port";//"ip or domain name:port"
            MemcachedClient client = null;
            try
            {
                client = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(connectionaddress));
                String key = "memcached";//向Memcached中存一个key为"memcached"的数据
                String value = "Hello World";//value为Hello World
                int expireTime = 5; // 过期时间,单位s; 从写入时刻开始计时,超过 expireTime s后,该数据过期失效,无法再读出;
                doExcute(client, key, value, expireTime);//执行操作
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    
        /**
         *向Memcached写数据方法
         */
        private static void doExcute(MemcachedClient client, String key, String value, int expireTime)
        {
            try
            {
                OperationFuture<Boolean> future = client.set(key, expireTime, value);
                future.get();// spymemcached set()是异步的,future.get() 等待cache.set()操作结束,也可以不等待,用户根据自己需求选择;
                System.out.println("Set操作成功");
                System.out.println("Get操作:" + client.get(key));
                Thread.sleep(6000);//等待6000毫秒,即6秒,该数据将会过期失效,无法再读出
                System.out.println("6秒后再执行Get操作:" + client.get(key));
    
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            catch (ExecutionException e)
            {
                e.printStackTrace();
            }
            if (client != null)
            {
                client.shutdown();
            }
        }
    }
     
  6. 运行main函数,在Eclipse下的Console窗口可以看到如下结果。
    Set操作成功
    Get操作:Hello World
    6秒后再执行Get操作:null
原文地址:https://www.cnblogs.com/husterindg/p/9102133.html