使用Jedis连接redis服务 淡淡的烟草味﹌ 2022-04-23 07:26 202阅读 0赞 使用jedis很简单,引入jar包: <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> 连接单机版redis: @Test public void testJdisSingle() { Jedis jedis=new Jedis("121.76.231.88",6379); jedis.set("key1", "testkevvv"); String string = jedis.get("key1"); System.out.println(string); jedis.close(); } 在云服务器上启动redis单机服务: ./redis-server redis.conf 测试的时候报错,无法连接,经验证,需要一下配置: > 1.确保云服务器开启了6379的端口,设置开启 > 2.redis.conf , 注释bind 127.0.0.1这一行 > 3.protected-mode yes 改成 protected-mode no 重启,再访问,成功! 注意: redis.conf中bind的含义为,bind配置了什么ip,redis就会监听本机的该IP,外网就得访问bind里面配置的ip才访问到redis服务 比如,一台主机,可能会有多张网卡,或者对应多网段内网的Ip,公网IP等,也就意味着其他机器可以通过多个IP地址访问到这台主机 若配置了127.0.0.1,那么任何外网机器访问127.0.0.1就访问到该机器本地了,也就确保了redis服务只能在本机访问 若注释掉这一行,redis则会监听本服务器所有的IP,这样外网和本机就都可以使用redis服务了 但是这样不太安全,建议开启密码验证 PS:我使用的是阿里云,配置了阿里云的公网Ip, 例如bind 124.32.45.22 ,但是外网却无法访问?? 使用jedispool连接池: @Test public void testJedisPool() { //创建jedis连接池 JedisPool pool = new JedisPool("120.77.204.80", 6379); //从连接池中获得Jedis对象 Jedis jedis = pool.getResource(); String string = jedis.get("key1"); System.out.println(string); //关闭jedis对象 jedis.close(); pool.close(); } JedisCluster连接集群cluster //集群cluster测试 @Test public void testJedisCluster() throws IOException { HashSet<HostAndPort> nodes = new HashSet<>(); nodes.add(new HostAndPort("120.77.204.80", 7001)); nodes.add(new HostAndPort("120.77.204.80", 7002)); nodes.add(new HostAndPort("120.77.204.80", 7003)); nodes.add(new HostAndPort("120.77.204.80", 7004)); nodes.add(new HostAndPort("120.77.204.80", 7005)); nodes.add(new HostAndPort("120.77.204.80", 7006)); JedisCluster cluster = new JedisCluster(nodes); cluster.set("key1", "1000"); String string = cluster.get("key1"); System.out.println(string); cluster.close(); } 出现错误: java.lang.NumberFormatException: For input string: "6379@16379" 原因是jedis和redis版本不匹配,redis是5.0的,所以将使用的jedis-2.8.0.jar包换成jedis-2.9.0.jar即可
还没有评论,来说两句吧...