Jedis介绍:Java Redis 客户端库

1.准备 

Java 1.8 环境;

Maven 环境;

开启 redis 服务;


2.pom.xml

<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>com.learn.redis</groupId>

    <artifactId>data-redis</artifactId>

    <version>1.0.0</version>

    <packaging>jar</packaging>



    <name>data-redis</name>



    <properties>

        <springframework.version>4.0.6.RELEASE</springframework.version>

    </properties>



    <dependencies>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-core</artifactId>

            <version>${springframework.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-context</artifactId>

            <version>${springframework.version}</version>

        </dependency>

        <dependency>

            <groupId>redis.clients</groupId>

            <artifactId>jedis</artifactId>

            <version>3.2.0</version>

        </dependency>

    </dependencies>

    <build>

        <pluginManagement>

            <plugins>

                <plugin>

                    <groupId>org.apache.maven.plugins</groupId>

                    <artifactId>maven-compiler-plugin</artifactId>

                    <version>3.7.0</version>

                    <configuration>

                        <source>1.8</source>

                        <target>1.8</target>

                    </configuration>

                </plugin>

            </plugins>

        </pluginManagement>

    </build>



</project>


3. Redis 数据结构

3.1 Strings

Jedis jedis = new Jedis();

// Strings

jedis.set("city:street", "hzjc");

String street = jedis.get("city:street");

System.out.println(street);


3.2 Lists

// Lists

jedis.lpush("city:list", "hz");

jedis.lpush("city:list", "sh");

List cityList = jedis.lrange("city:list", 0, -1);

System.out.println(cityList.toString());

jedis.rpop("city:list");

cityList = jedis.lrange("city:list", 0, -1);

System.out.println(cityList.toString());


3.3 Sets

// Sets

jedis.sadd("city:name", "上海");

jedis.sadd("city:name", "杭州");

jedis.sadd("city:name", "北京");

jedis.sadd("city:name", "杭州");

Set cityName = jedis.smembers("city:name");

System.out.println(cityName.toString());


3.4 Hash

// Hash

jedis.hset("city:province", "hb", "武汉");

jedis.hset("city:province", "gd", "东莞");

jedis.hset("city:province", "zj", "杭州");

String wh = jedis.hget("city:province", "hb");

System.out.println(wh);

Map cityProvince = jedis.hgetAll("city:province");

System.out.println(cityProvince.toString());


3.5 Sorted

// Sorted

jedis.zadd("city:ranking", 2, "武汉");

jedis.zadd("city:ranking", 1, "杭州");

jedis.zadd("city:ranking", 3, "东莞");

Set cityRanking = jedis.zrange("city:ranking", 0, -1);

System.out.println(cityRanking.toString());

Set cityRankingRev = jedis.zrevrange("city:ranking", 0, -1);

System.out.println(cityRankingRev);


3.6 Transaction

// Transaction

Transaction transaction = jedis.multi();

transaction.sadd("city:name", "三亚");

transaction.sadd("city:name", "大理");

transaction.sadd("city:name", "苏州");

transaction.exec();

cityName = jedis.smembers("city:name");

System.out.println(cityName);


3.7 Pipeline

// Pipeline

Pipeline pipeline = jedis.pipelined();

pipeline.sadd("city:name", "香港");

pipeline.zadd("city:ranking", 5, "三亚");

pipeline.zadd("city:ranking", 6, "云南");

Response<Boolean> cityExists = pipeline.sismember("city:name", "香港");

Response<Set<String>> citys = pipeline.zrange("city:ranking", 0, -1);

pipeline.sync();



Boolean ex = cityExists.get();

Set cr = citys.get();



System.out.println(ex);

System.out.println(cr);


3.8 Publish - Subscrible

// Publish - Subscrible

// 阻塞式方法,持续监听状态 - 以线程方式启动

MessagePubSub messagePubSub = new MessagePubSub();

new Thread(() -> jedis.subscribe(messagePubSub, "channel")).start();



st();



new Thread(() -> {

    Jedis j = new Jedis();

    j.publish("channel", "Hello, Jides");

    messagePubSub.unsubscribe();

}).start();



public static void st() {

    try {

        Thread.sleep(1000);

    } catch (InterruptedException e) {

        e.printStackTrace();

    }

}



class MessagePubSub extends JedisPubSub {

    @Override    

    public void onMessage(String channel, String message) {

        System.out.println("handle: " + message);

    }

}


3.9 Clear

// 清空

jedis.flushAll();


4.0 Connection Pooling

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;



import java.time.Duration;



public class JedisPoolUtil {



    private final static JedisPool jedisPool = new JedisPool(buildPoolConfig(), "localhost");



    private static JedisPoolConfig buildPoolConfig() {

        final JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

        // 最大连接

        jedisPoolConfig.setMaxTotal(64);

        // 最大等待连接

        jedisPoolConfig.setMaxIdle(64);

        // 最小等待连接

        jedisPoolConfig.setMinIdle(32);

        // 检测连接可用性

        jedisPoolConfig.setTestOnBorrow(true);

        // 检测返回池连接的可用性

        jedisPoolConfig.setTestOnReturn(true);

        // true:连接空闲时验证

        jedisPoolConfig.setTestWhileIdle(true);

        // 池中连接剔除最小空闲时间

        jedisPoolConfig.setMinEvictableIdleTimeMillis(Duration.ofSeconds(60).toMillis());

        // 剔除连接、重置池大小......的间隔时间

        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(Duration.ofSeconds(30).toMillis());

        // 不再使用

        jedisPoolConfig.setNumTestsPerEvictionRun(3);

        // 连接用尽时阻塞

        jedisPoolConfig.setBlockWhenExhausted(true);

        return jedisPoolConfig;

    }



    static Jedis getJedis() throws JedisPoolException {

        if (jedisPool != null) {

            return jedisPool.getResource();

        } else {

            throw new JedisPoolException("Jedis pool create fail.");

        }

    }



    static class JedisPoolException extends Exception {

        public JedisPoolException(String s) {

            super(s);

        }

    }

}



// 以 try - with 方式,可以自动释放资源

import redis.clients.jedis.Jedis;



public class JedisPoolBasic {



    public static void main(String[] args) {

        try(Jedis jedis = JedisPoolUtil.getJedis()) {

            jedis.set("company:employee", "zhanh");

            String employee = jedis.get("company:employee");

            System.out.println(employee);

        } catch (JedisPoolUtil.JedisPoolException e) {

            e.printStackTrace();

        }

    }

}


4.1 Redis 集群

redis 集群部署:https://redis.io/topics/cluster-spec

jedis 集群使用:https://github.com/xetorthio/jedis#jedis-cluster

使用集群时,不能使用事务 Transaction 和 管道 Pipeline。


总结:

介绍了 Redis 基本数据结构,具体 API 建议直接查 Redis API 文档,很详细。Jedis 都是与之对应的。


 

展开阅读全文