美文网首页
Jedis第一个Demo

Jedis第一个Demo

作者: Eve0 | 来源:发表于2017-08-16 22:06 被阅读0次

代码部分

 package com.test.jedis;

 import org.junit.Test;
 
 import redis.clients.jedis.Jedis;
 import redis.clients.jedis.JedisPool;
 import redis.clients.jedis.JedisPoolConfig;

 public class JedisTest {
       @Test
       public void testJedis() {
             Jedis jedis = new Jedis("192.168.1.107", 6379);
             jedis.set("name", "admin");
             String name = jedis.get("name");
             System.out.println("name:" + name);
             jedis.close();
         }

       @Test
       public void testJedisPool() {//使用连接池方式
             JedisPoolConfig config = new JedisPoolConfig();
             config.setMaxIdle(23);
             config.setMaxTotal(100);

             JedisPool pool = new JedisPool(config, "192.168.1.107", 6379);
             Jedis jedis = null;
             try {
                   jedis = pool.getResource();
                   jedis.set("name", "wakaka");
                   String name = jedis.get("name");
                   System.out.println("#name:" + name);
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                if (jedis != null) {
                    jedis.close();
                 }
                if (pool != null) {
                    pool.close();
                  }
             }
 
      }

}

首次运行报错:connectTimeOut连接数据库超时,检查了一下,虚拟机中centos7的Redis的端口被防火墙过滤了。
解决方法

  1. 将6379端口加入白名单
    vi /etc/sysconfig/iptables
# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

6379端口这一行是新增的内容,即
-A INPUT -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT

  1. 重启服务
    service iptables restart

  2. Windows的cmd打开,测试192.168.1.107的6379端口
    telnet 192.168.1.107 6379
    如果显示连接成功,--->END

    如果显示连接失败,请继续往下看步骤4

  3. 检查192.168.1.107中Redis的配置文件
    vi redis.conf
    找到bind 127.0.0.1修改为192.168.1.107。
    再次回到步骤3,测试成功-->END

正在学习Redis,记作笔记,有误请指出。谢谢

相关文章

网友评论

      本文标题:Jedis第一个Demo

      本文链接:https://www.haomeiwen.com/subject/klywrxtx.html