1 package com.test.jedis; 2 3 import org.junit.Test; 4 5 import redis.clients.jedis.Jedis; 6 import redis.clients.jedis.JedisPool; 7 import redis.clients.jedis.JedisPoolConfig; 8 9 public class JedisTest { 10 @Test 11 public void testJedis() { 12 Jedis jedis = new Jedis("192.168.1.107", 6379); 13 jedis.set("name", "admin"); 14 String name = jedis.get("name"); 15 System.out.println("name:" + name); 16 jedis.close(); 17 } 18 19 @Test 20 public void testJedisPool() {//使用连接池方式 21 22 JedisPoolConfig config = new JedisPoolConfig(); 23 config.setMaxIdle(23); 24 config.setMaxTotal(100); 25 26 JedisPool pool = new JedisPool(config, "192.168.1.107", 6379); 27 Jedis jedis = null; 28 try { 29 jedis = pool.getResource(); 30 jedis.set("name", "wakaka"); 31 String name = jedis.get("name"); 32 System.out.println("#name:" + name); 33 } catch (Exception e) { 34 e.printStackTrace(); 35 } finally { 36 if (jedis != null) { 37 jedis.close(); 38 } 39 if (pool != null) { 40 pool.close(); 41 } 42 } 43 44 } 45 46 }
首次运行报错: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
红色字部分为新加入的部分,即
-A INPUT -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT
2.重启服务
service iptables restart
3.Windows的cmd打开,测试192.168.1.107的6379端口
telnet 192.168.1.107 6379
如果显示连接成功,--->END
如果显示连接失败,请继续往下看步骤4
4.检查192.168.1.107中Redis的配置文件
vi redis.conf
找到bind 127.0.0.1修改为192.168.1.107。
再次回到步骤3,测试成功-->END
正在学习Redis,记作笔记,有误请指出。谢谢
时间: 2024-10-18 00:35:36