Jedis: Java连接redis服务


提示:以下是本篇文章正文内容,Redis系列学习将会持续更新

一、编程语言与 Redis

● Java 语言连接 redis 服务   Jedis   SpringData Redis   Lettuce

● C 、C++ 、C# 、Erlang、Lua 、Objective - C 、Perl 、PHP 、Python 、Ruby 、Scala

● 可视化连接 redis 客户端   Redis Desktop Manager   Redis Client   Redis Studio

二、Jedis 连接

2-1 准备工作:

● jar 包导入   下载地址:

● 基于 maven

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

2-2 客户端连接 redis:

// 连接 redis
Jedis jedis = new Jedis("localhost", 6379);

// 操作 redis
jedis.set("name", "itheima");
jedis.get("name");

// 关闭连接
jedis.close();

三、JedisPool 连接池

JedisPool:Jedis提供的连接池技术。

// poolConfig: 连接池配置对象
// host: redis服务地址
// port: redis服务端口号
public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port) {
          
   
    this(poolConfig, host, port, 2000, (String)null, 0, (String)null);
}

3-1 封装连接参数: redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.maxTotal=30
redis.maxIdle=10

3-2 定义连接池:

public class JedisUtils {
          
   

    private static JedisPoolConfig jpc;
    private static JedisPool jp;
    private static String host;
    private static int port;
    private static int maxTotal;
    private static int maxIdle;

	// 3-2 加载配置信息:
    // 静态代码块初始化资源
    static {
          
   
        // 读取配置文件, 获得参数值
        ResourceBundle rb = ResourceBundle.getBundle("redis");
        host = rb.getString("redis.host");
        port = Integer.parseInt(rb.getString("redis.port"));
        maxTotal = Integer.parseInt(rb.getString("redis.maxTotal"));
        maxIdle = Integer.parseInt(rb.getString("redis.maxIdle"));

        jpc = new JedisPoolConfig();
        jpc.setMaxTotal(maxTotal);
        jpc.setMaxIdle(maxIdle);
        jp = new JedisPool(jpc, host, port);
    }

    // 3-3 获取连接:
    // 对外访问接口,提供jedis连接对象,连接从连接池获取
    public static Jedis getJedis() {
          
   
        return jp.getResource();
    }
}

四、可视化客户端

Redis Desktop Manager

官网下载:


总结: 提示:这里对文章进行总结: 本文是对Jedis的学习,如何连接Java和redis,Redis类的使用,RedisPool连接池的使用,以及可视化客户端的使用。之后的学习内容将持续更新!!!

经验分享 程序员 微信小程序 职场和发展