Redis(四)之Jedis

在maven项目中,引入如下依赖:

<!-- Redis客户端 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

测试代码

public class JedisTest {
    //单机版测试
    @Test
    public void testJedisSingle() throws Exception {
        //创建一个Jedis对象
        Jedis jedis = new Jedis("192.168.41.132", 6379);
        jedis.set("test", "hello jedis");
        String string = jedis.get("test");
        System.out.println(string);
        jedis.close();
    }
    //使用连接池
    @Test
    public void testJedisPool() throws Exception {
        //创建一个连接池对象
        //系统中应该是单例的。
        JedisPool jedisPool = new JedisPool("192.168.41.132", 6379);
        //从连接池中获得一个连接
        Jedis jedis = jedisPool.getResource();
        String result = jedis.get("test");
        System.out.println(result);
        //jedis必须关闭
        jedis.close();

        //系统关闭时关闭连接池
        jedisPool.close();
    }
    //连接redis集群
    @Test
    public void testJedisCluster() throws Exception {
        //创建一个JedisCluster对象
        Set<HostAndPort> nodes = new HashSet<>();
        nodes.add(new HostAndPort("192.168.41.132", 7001));
        nodes.add(new HostAndPort("192.168.41.132", 7002));
        nodes.add(new HostAndPort("192.168.41.132", 7003));
        nodes.add(new HostAndPort("192.168.41.132", 7004));
        nodes.add(new HostAndPort("192.168.41.132", 7005));
        nodes.add(new HostAndPort("192.168.41.132", 7006));
        //在nodes中指定每个节点的地址
        //jedisCluster在系统中是单例的。
        JedisCluster jedisCluster = new JedisCluster(nodes);
        jedisCluster.set("name", "zhangsan");
        jedisCluster.set("value", "100");
        String name = jedisCluster.get("name");
        String value = jedisCluster.get("value");
        System.out.println(name);
        System.out.println(value);

        //系统关闭时关闭jedisCluster
        jedisCluster.close();
    }
}

问题

1、连接被拒绝

这里写图片描述

  • 服务未启动:

执行:lsof -i :6379

isof-i命令查看是否开启进程

结果如下,证明开启

COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME

redis-ser 11560 root    4u  IPv4  69938      0t0  TCP *:6379 (LISTEN)
  • 查看是否将默认只能本地访问redis改为所有IP均可以访问

进入redis.conf配置文件

bind 127.0.0.1 改为 bind 0.0.0.0

查看端口号是否为6379
port 6379

重启redis:
关闭:./bin/redis-cli shutdown
开启:./bin/redis-server ./redis.conf

  • 关闭防火墙

service iptables stop

猜你喜欢

转载自blog.csdn.net/code_shadow/article/details/80873740