package util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 JedisPool工具类
    加载配置文件,配置连接池的参数
    提供获取连接的方法

 */
public class JedisPoolUtils {

    private static JedisPool jedisPool;

    static{
        //读取配置文件
        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        //创建Properties对象
        Properties pro = new Properties();
        //关联文件
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取数据,设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));

        //初始化JedisPool
        jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
    }
    /**
     * 获取连接方法
     */
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}
package util;

import redis.clients.jedis.Jedis;

import java.util.HashMap;

public class JedisPoolUtilsTest {
    public static void main(String[] args) {
        Jedis jedis = JedisPoolUtils.getJedis();

        jedis.set("name","yc");
        System.out.println(jedis.get("name"));

        HashMap<String,String> student = new HashMap();
        student.put("name","yc");
        student.put("age","12");
        jedis.hmset("student",student);
        System.out.println(jedis.hgetAll("student"));

        jedis.lpush("class","01","02","03");
        System.out.println(jedis.lrange("class",1,-1));

        jedis.sadd("abc","a","b","c");
        System.out.println(jedis.smembers("abc"));

        jedis.zadd("qwe",12,"q");
        System.out.println(jedis.zrangeByScore("qwe",0,-3));
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>untitled</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>


</project>
host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10
最后修改:2021 年 05 月 28 日 01 : 44 PM
如果觉得我的文章对你有用,请随意赞赏