【Jedis】如何用Java操作Redis——Jedis+连接池+工具类

Jedis

Jedis是一款java操作redis数据库的工具(类似于JDBC操作MySql数据库,但更加简单)
 
下面,将演示Jedis的快速入门,以及操作string、hash、list、set、zset等value数据结构的键值对

------------------------------------------------- 快速入门 -----------------------------------------------------

1.导入jar包
2.使用:

Jedis jedis = new Jedis("localhost", 6379);			// 获取连接(可以空参,默认值的主机和端口号就是localhost:6379)
jedis.set("name", "Alice");							// 操作Redis
jedis.close()										// 关闭连接

☑ 下面仅仅演示"最简单最常用的命令",其他命令的"方法名"都是由"Redis原生命令"转化来的

------------------------------------------------- string -----------------------------------------------------
jedis.set("username", "Alice");				// value不能写成数字整形,没有这种重载(233 写成 "233")
jedis.get("username");
jedis.setex("username", 10, "Alice");		// 指定过期时间为10s

------------------------------------------------- hash -----------------------------------------------------
jedis.hset("myhash", "name", "Alice");
jedis.hset("myhash", "age", "12");

jedis.hget("myhash", "name");
jedis.hgetAll("myhash");					// 返回Map<String, String>

------------------------------------------------- list -----------------------------------------------------
jedis.lpush("mylist", "a", "b", "c");
jedis.rpush("mylist", "a", "b", "c");
jedis.lpop("mylist");
jedis.rpop("mylist");

jedis.lrange("mylist", 0, -1);				// 返回List<String>

------------------------------------------------- set -----------------------------------------------------
jedis.sadd("myset", "Alice", "Cocoa","Hana");
jedis.smembers("myset");					// 返回Set<String>

------------------------------------------------- zset -----------------------------------------------------

jedis.zadd("myzset", 100, "Alice");
jedis.zadd("myzset", 300, "Cocoa");
jedis.zadd("myzset", 900, "Hana");
jedis.zrange("myzset", 0, -1);				// 返回Set<String>

 
 

JedisPool——Jedis连接池

使用JedisPool连接池无需额外导入jar包(Jedis的jar包就够) ! ! !

// 1.创建连接池对象(空参)
JedisPool jedisPool = new JedisPool();
// 2.获取连接
Jedis jedis = jedisPool.getResource();
// 3.使用
jedis.set("loli", "Alice");
// 4.释放连接
jedis.close();
// 0.创建一个配置对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(50);
config.setMaxIdle(10);
// 1.创建连接池对象(带参)
JedisPool jedisPool = new JedisPool(config, "localhost", 6379);
// 2.获取连接
Jedis jedis = jedisPool.getResource();
// 3.使用
jedis.set("loli", "Alice");
// 4.归还连接
jedis.close();

 
 

JedisPoolUtils工具类

上面我们通过JedisPoolConfig配置对象直接赋值来进行连接池的配置,这显然不是最佳的选择
 
最好将配置信息写在配置文件中,在生成连接池时加载配置文件——这些行为,写在一个工具类的静态代码块中是一个不错的选择

--------------------------------------------- jedis.properties ------------------------------------------------
ip=xxxxxx  				# redis服务器的IP    
port=6379				# redis服务器的Port   
maxTotal=1000    		# 最大活动对象数  
maxIdle=100  			# 最大能够保持idle状态的对象数   
minIdle=50				# 最小能够保持idle状态的对象数        
maxWaitMillis=10000		# 当池内没有返回对象时,最大等待时间        
--------------------------------------------- jedisUtils.java ------------------------------------------------
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.*;
import java.util.Properties;

/**
 * JedisPool工具类
 *      1.加载配置文件,配置连接池的参数
 *      2.提供获取连接的方法
 */
public class JedisPoolUtils {

    private static JedisPool jedisPool;

    /**
     * 静态代码块————加载配置文件,new出连接池
     */
    static {
        // 1.读取配置文件字节流 → 创建Properties对象 → 关联(load)文件
        //InputStream stream = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        InputStream stream = null;
        try {
            stream = new FileInputStream(new File("src/jedis.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Properties pro = new Properties();
        try {
            pro.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 2.获取配置,设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));

        // 3.初始化jedisPool
        jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
    }

    /**
     * 静态方法————获取连接
     * @return
     */
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }

}

 
 

追加:JedisPoolUtils工具类引用properties的路径问题

/**
* 静态代码块————加载配置文件,new出连接池
*/
static {
    // step1————读取配置文件字节流--创建properties对象--关联(load)
    InputStream stream = null;
    Properties properties = new Properties();
    try {
        URL url = Class.forName(JedisUtils.class.getName()).getClassLoader().getResource("jedis.properties");
        stream = new FileInputStream(url.getFile());
        properties.load(stream);
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }

    // step2————获取配置,设置到JedisPoolConfig中
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
    config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));

    // step3————初始化pool连接池
    jedisPool = new JedisPool(config, properties.getProperty("ip"), Integer.parseInt(properties.getProperty("port")));

}

 

 

 

 

 

 

 
 

 
 

 
 

 

End ♬

by a Lolicon ✪

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JedisUtil是一个Java Redis缓存工具类,它封装了Jedis客户端的基本操作,使得使用Redis缓存更加简单方便。 以下是JedisUtil的示例代码: ``` import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisUtil { private static JedisPool jedisPool; static { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(1000); jedisPoolConfig.setMaxIdle(100); jedisPool = new JedisPool(jedisPoolConfig, "localhost", 6379); } public static void set(String key, String value) { try (Jedis jedis = jedisPool.getResource()) { jedis.set(key, value); } } public static String get(String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.get(key); } } public static void del(String key) { try (Jedis jedis = jedisPool.getResource()) { jedis.del(key); } } public static void expire(String key, int seconds) { try (Jedis jedis = jedisPool.getResource()) { jedis.expire(key, seconds); } } public static boolean exists(String key) { try (Jedis jedis = jedisPool.getResource()) { return jedis.exists(key); } } } ``` 在上面的代码中,我们使用了JedisPool来管理Jedis连接,它的作用是维护一定数量的Jedis连接,以便在需要时从中获取连接,减少了创建和关闭连接的开销。 在使用JedisUtil时,我们只需要调用set、get、del、expire和exists等方法,就可以完成对Redis缓存的操作。 例如,要将一个键值对("name", "Tom")存入Redis中,可以使用以下代码: ``` JedisUtil.set("name", "Tom"); ``` 要获取键为"name"的值,可以使用以下代码: ``` String name = JedisUtil.get("name"); ``` 同时,JedisUtil还提供了删除、设置过期时间和判断键是否存在等方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值