Jedis connect to Redis in Java

Jedis connect to Redis

The first step: create a project, import dependencies

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.7.2</version>
</dependency>

note:

1) Confirm whether the remote server can be pinged: ping the ip address of vm

Insert picture description here

2) Confirm whether the firewall is closed or allowed

service iptables stop

service iptables status

Step 2: Link the server

Option One

Single instance link

Jedis jedis = new Jedis(“ip地址”, 端口号);//建立链接

Core code

public static void main(String[] args) {
    Jedis jedis=new Jedis("192.168.197.129",6379);
    //设置值
    jedis.set("java001","java工程师");
    String java001 = jedis.get("java001");
    System.out.println(java001);
}

Common exceptions:

Insert picture description here

solution:

The ip of the virtual machine client connection is 127.0.0.1, which means the connected machine, and other machines cannot connect. Here you need to modify the configuration file and change the connection address to the address of the virtual machine.

Modify the bind connection address in the redis.conf file and change the connection address to the ip of your own virtual machine

bind 192.168.197.129

Restart the service, Jedis can connect normally

Console printing in Idea:

Insert picture description here

Storage on the server:

Insert picture description here

Option two: connection pool

The jedis connection pool connection will be integrated later using Spring configuration files.

  //1.创建连接池配置的工具类对象
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(10);//jedis连接的空闲数
        jedisPoolConfig.setMaxIdle(20);//总的连接数
        JedisPool jedisPool = null;
        Jedis jedis = null;
        try{
            //2.创建连接池对象
            jedisPool = new JedisPool(jedisPoolConfig,"192.168.87.129",6379);
            //3.获得jedis资源
            jedis = jedisPool.getResource();
            //4.操作数据
            jedis.set("stu1","student1");
            String stu1 = jedis.get("stu1");
            System.out.println("stu1="+stu1);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(jedis!=null){
                jedis.close();
            }
            if(jedisPool!=null){
                jedisPool.close();
            }
        }



    }

Server storage confirmation:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43515837/article/details/113095849