redis之Java Jedis 的使用(使用maven引入)

maven依赖:

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

 

jedis的操作的api跟redis-cli命令行极其相似

import redis.clients.jedis.Jedis;

import java.util.*;

public class TestRedis {
    public static void main(String[] args) {
        //ip 端口
        Jedis jedis = new Jedis("你的ip", 6379);
        //密码
        jedis.auth("mypassword");
        //测试连接
        String ping = jedis.ping();
        System.out.println(ping);
        //jedis 使用数据库1
        jedis.select(1);
        //字符串存取
        String set = jedis.set("k1", "k2");
        System.out.println(set);
        String k1 = jedis.get("k1");
        System.out.println(k1);
        //不存在的键
        System.out.println(jedis.get("k5"));
        //键是否存在
        System.out.println(jedis.exists("k5"));
        //键遍历
        Set<String> keys = jedis.keys("*");
        for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
            String key = (String) iterator.next();
            System.out.println(key);
        }
        //批量存取
        jedis.mset("test-redis-str1","v1","test-redis-str2","v2","test-redis-str3","v3");
        System.out.println(jedis.mget("test-redis-str1","test-redis-str2","test-redis-str3"));
        //set
        jedis.sadd("orders","jd001");
        jedis.sadd("orders","jd002");
        jedis.sadd("orders","jd003");
        Set<String> set1 = jedis.smembers("orders");
        for (Iterator iterator = set1.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println(string);
        }
        jedis.srem("orders","jd002");
        Set<String> set2 = jedis.smembers("orders");
        for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println(string);
        }
        //hash
        jedis.hset("hash1","userName","lisi");
        System.out.println(jedis.hget("hash1","userName"));
        Map<String,String> map = new HashMap<String,String>();
        map.put("telphone","13810169999");
        map.put("address","atguigu");
        map.put("email","abc@163.com");
        jedis.hmset("hash2",map);
        List<String> result = jedis.hmget("hash2", "telphone","email");
        for (String element : result) {
            System.out.println(element);
        }
        //zset
        jedis.zadd("zset01",60d,"v1");
        jedis.zadd("zset01",70d,"v2");
        jedis.zadd("zset01",80d,"v3");
        jedis.zadd("zset01",90d,"v4");
        Set<String> s1 = jedis.zrange("zset01",0,-1);
        for (Iterator iterator = s1.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println(string);
        }

    }
}

 

posted @ 2020-03-24 16:57  护花使者  Views(4296)  Comments(0Edit  收藏  举报