使用Java操作Redis

Java操作Redis

  1. 添加依赖
        
            redis.clients
            jedis
            ${jedis.version}
        
  1. 连接Redis
    (1)启动Redis服务
    (2)连接
import redis.clients.jedis.Jedis;

/**
 * 类功能描述:
 *
 * @author:tyro_learner
 * @createTime:2018/11/7 9:16
 */
public class ConnectionRedisServer {
    public static final String REDIS_HOST = "192.168.215.100";
    public static final int REDIS_POST = 6379;

    public static void main(String[] args) {
        Jedis jedis = new Jedis(REDIS_HOST, REDIS_POST);
        System.out.println(jedis.ping());
        jedis.close();
    }
}

结果输出:PONG,连接成功
3. 简单操作

import redis.clients.jedis.Jedis;

/**
 1. 类功能描述:
 2.  3. @author:tyro_learner
 4. @createTime:2018/11/7 9:16
 */
public class ConnectionRedisServer {
    public static final String REDIS_HOST = "192.168.215.100";
    public static final int REDIS_POST = 6379;

    public static void main(String[] args) {
        Jedis jedis = new Jedis(REDIS_HOST, REDIS_POST);
        jedis.set("test_1", "1");
        System.out.println(jedis.get("test_1"));
        jedis.close();
    }
}

输出:1
可能出现的问题:

  1. Connection refused: connect
    解决方法:修改redis.conf
    bind 192.168.215.100 # 修改为自己的ip
  2. java.net.SocketTimeoutException: connect timed out
    连接超时:可能原因是端口没有开放
    firewall-cmd --query-port=6379/tcp
    结果为no,执行以下命令
    firewall-cmd --add-port=6379/tcp
    以上两条命令只适用于CentOs7

你可能感兴趣的:(redis)