Redis学习笔记(3)—— Jedis入门

一、Jedis介绍

  Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持,比如Java、C、C#、C++、php、Node、js、Go等。

  在官方网站里列的一些Java客户端,有jedis、Redisson、Jredis等,其中官方推荐使用jedis,在企业中用的最多的就是Jedis。

二、Java连接Redis

2.1 导入jar包

  • commons-pool2-2.3.jar
  • jedis-2.7.0.jar

2.2 单实例连接

    @Test
    public void testJedisSingle() throws Exception {
        // 1.设置ip地址和端口号
        Jedis jedis = new Jedis("192.168.25.129", 6379);
        // 2.设置数据
        jedis.set("name", "zhangsan");
        // 3.获得数据
        String name = jedis.get("name");
        System.out.println(name);
        // 4.释放资源
        jedis.close();
    }    

   注:如果执行上面代码时抛出如下异常

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeOutException: connect timed out

   必须关闭Linux防火墙

service iptables stop

2.3 连接池连接

  @Test
    public void testJedisPool() throws Exception {
        // 1.获得连接池配置对象,设置配置项
        JedisPoolConfig config = new JedisPoolConfig();
        // 1.1 最大连接数
        config.setMaxTotal(30);
        // 1.2 最大空闲连接数
        config.setMaxIdle(10);

        // 2.获得连接池
        JedisPool jedisPool = new JedisPool(config, "192.168.25.129", 6379);

        // 3.获得核心对象
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            // 4.设置数据
            jedis.set("name", "lisi");
            // 5.获得数据
            String name = jedis.get("name");
            System.out.println(name);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
            // 虚拟机关闭时,释放pool资源
            if (jedisPool != null) {
                jedisPool.close();
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/yft-javaNotes/p/10082711.html