Redis学习8-Jedis 操作 Redis


  

13 Jedis 操作 Redis

13.1 Jedis简介

使用 Redis 官方推荐的 Jedis,在 java 应用中操作 Redis。Jedis 几乎涵盖了 Redis 的所有 命令。操作 Redis 的命令在 Jedis 中以方法的形式出现。jedis 完全兼容 redis 2.8.x and 3.x.x
   ⚫ Jedis 源码:`https://github.com/xetorthio/jedis
   ⚫ api 文档: http://xetorthio.github.io/jedis/
   ⚫ 下载:http://search.maven.org/ ,搜索 jedis

13.2 下载Jedis

浏览器打开:http://search.maven.org/ ,搜索 jedis。在 Download 处,点击 jar

13.2 下载Commons-Pool

Jedis 对象并不是线程安全的,在多线程下使用同一个 Jedis 对象会出现并发问题。为 了避免每次使用 Jedis 对象时都需要重新构建,Jedis 提供了 JedisPool。JedisPool 是基于 Commons Pool 2 实现的一个线程安全的连接池
浏览器打开:http://search.maven.org/ ,搜索 commons-pool2。在 Download 处,点击 jar

13.3 Jedis 操作Redis

13.3.1 Jedis 操作 String类型

	<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.3</version>
        </dependency>
    </dependencies>
public class RedisString {
    public static void main(String[] args) {
        //创建Jedis连接对象
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        //添加字符串
        jedis.set("username", "zhangsan");
        String username = jedis.get("username");
        System.out.println(username);

        //追加内容
        jedis.append("username", "-lisi");
        username = jedis.get("username");
        System.out.println(username);

        //一次设置多个值
        jedis.mset("k1", "v1", "k2", "v2");
        List<String> mget = jedis.mget("k1", "k2", "k3");
        mget.forEach(s -> System.out.println(s));

    }
}
zhangsan
zhangsan-lisi
v1
v2
null

Process finished with exit code 0

13.3.2 Jedis 操作 Hash类型

public class RedisHash {
    public static void main(String[] args){
        JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.hset("username","zhangsan","zhangsan");
            System.out.println(jedis.hget("username","zhangsan"));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //使用完的对象,放回连接池
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
zhangsan
public class RedisHash2 {
    public static void main(String[] args) {
        JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            Map<String,String> map = new HashMap<>();
            map.put("username","zhangsan");
            map.put("userId","123");
            map.put("loginTime","2019-12-7");
            jedis.hmset("loginInfo",map);

            List<String> mget = jedis.hmget("loginInfo", "userId","username");
            mget.forEach(s -> System.out.println(s));

            //返回是否存在某个字段
            System.out.println(jedis.hexists("loginInfo","userId"));

            //返回所有的字段名
           jedis.hkeys("loginInfo").forEach(s -> System.out.println(s));

           //删除某个字段
            jedis.hdel("loginInfo","userId");

            //获取所有的filed数量
            System.out.println(jedis.hlen("loginInfo"));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //使用完的对象,放回连接池
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
123
zhangsan
true
userId
username
loginTime
2
public class RedisUtil {
    //定义连接池对象
    private static JedisPool pool = null;

    //创建连接池
    public static JedisPool open(String host, int port) {
        if (pool == null) {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            //设置最大的Jedis的实例数(连接池种存放的是Jedis实例,默认数为8)
            jedisPoolConfig.setMaxTotal(10);
            //设置最大的空闲实例数,该设置可以保留足够的连接,快速的获取到Jedis对象
            jedisPoolConfig.setMaxIdle(3);
            //提前检查Jedis对象,为Ture获取的Jedis一定是可用的
            jedisPoolConfig.setTestOnBorrow(true);
            //创建Jedis连接池,没有密码时的创建方式
            pool = new JedisPool(jedisPoolConfig, host, port);

            //创建Jedis连接池,Redis有密码时的使用方式(超时时间,密码)
            //pool = new JedisPool(jedisPoolConfig,host,port,6 * 1000,"123456");
        }
        return pool;
    }
    public static void close(){
        if (pool != null) {
            pool.close();
        }
    }
}

13.3.3 Jedis 操作 List类型

public class ReidsList {
    public static void main(String[] args) {
        JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.lpush("list","1","2","3");
            List<String> list = jedis.lrange("list", 0, -1);
            list.forEach(s -> System.out.print(s + "  "));
            System.out.println("length:" + jedis.llen("list"));
            //在3的后边插入4
            jedis.linsert("list", BinaryClient.LIST_POSITION.AFTER,"3","4");
            list = jedis.lrange("list", 0, -1);
            list.forEach(s -> System.out.print(s + "  "));
            System.out.println();

            //列表右侧插入
            jedis.rpush("list","0");
            list = jedis.lrange("list", 0, -1);
            list.forEach(s -> System.out.print(s + "  "));
            System.out.println();

            //索引为0的元素为
            String index0 = jedis.lindex("list", 0);
            System.out.println(index0);
            System.out.println();

            //弹出左边的元素
            String lpop = jedis.lpop("list");
            System.out.println(lpop);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //使用完的对象,放回连接池
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
3  2  1  length:3
3  4  2  1  
3  4  2  1  0  
3

3

13.3.4 Jedis 操作 Set类型

public class RedisSet {
    public static void main(String[] args){
        JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.sadd("language","Java","C++","Python");
            jedis.smembers("language").forEach(s -> System.out.print(s + " "));

            //是否包含
            System.out.println(jedis.sismember("language","Java"));
            //返回数量
            System.out.println(jedis.scard("language"));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //使用完的对象,放回连接池
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
Java Python C++ true
3

13.3.5 Jedis 操作 ZSet类型

public class RedisZSet {
    public static void main(String[] args){
        JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            Map<String,Double> map = new HashMap<>();
            map.put("zhangan",100.0);
            map.put("lisi",99.3);
            map.put("wangwu",99.7);
            jedis.zadd("score",map);
            Set<String> score = jedis.zrangeByScore("score", "-inf", "+inf");
            score.forEach(s -> System.out.print(" " + s));
            System.out.println();

            Set<Tuple> score1 = jedis.zrangeByScoreWithScores("score", "-inf", "+inf");
            score1.forEach(s-> System.out.println(s.getElement()+"->"+s.getScore()));
            System.out.println(jedis.zcard("score"));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //使用完的对象,放回连接池
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}

 lisi wangwu zhangan
lisi->99.3
wangwu->99.7
zhangan->100.0
3

13.3.6 Jedis 使用事务

public class RedisTransaction {
    public static void main(String[] args){
        JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            Transaction multi = jedis.multi();
            multi.set("t1","v1");
            multi.mset("t2","v2","t3","v3");
            multi.dbSize();
            List<Object> exec = multi.exec();
            exec.forEach(s -> System.out.println(s));

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //使用完的对象,放回连接池
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
OK
OK
8
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值