Usage of five basic types of redis

Keywords: Jedis Redis Java REST

redis storage format

We all know the storage types supported by redis (String/List/Hash/Set/SortedSet), but not necessarily used in our work. I hope that through this article, we can know how to use redis in java and how to operate these data types by redis.

Basic Usage

Operate on redis through jedis (the Java client that encapsulates redis).

Jedis utility class

public class JedisPoolUtil {
    private static JedisPool pool = null;
    static {
        //Load profile
        InputStream in = JedisPoolUtil.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Failed to load file");
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //maximum connection
        poolConfig.setMaxTotal(Integer.parseInt( pro.get("redis.maxTotal").toString()));
        //Maximum number of idle connections
        poolConfig.setMaxIdle(Integer.parseInt( pro.get("redis.maxIdle").toString()));
        //Minimum free connections
        poolConfig.setMinIdle(Integer.parseInt( pro.get("redis.minIdle").toString()));
        pool = new JedisPool(poolConfig, pro.get("redis.url").toString(),Integer.parseInt( pro.get("redis.port")
                .toString()));
    }

    public static Jedis getJedis(){
        return pool.getResource();
    }
    public static void release(Jedis jedis){
        if(null != jedis){
            jedis.close();
        }
    }
}

redis profile

redis.maxTotal=100
redis.maxIdle=30
redis.minIdle=10
redis.url=192.168.202.200 
redis.port=6379

String test

public class StringTest {
    public  Jedis jedis = JedisPoolUtil.getJedis();
    @Test
    //Add and get
    public void fun(){
        jedis.set("num","1");
        System.out.println(jedis.get("num"));
    }
    @Test
    //Delete value
    public void fun1(){
        jedis.del("num");
        System.out.println(jedis.get("num"));
    }
    @Test
    //Self subtraction and self subtraction
    public void fun2(){
        jedis.set("num","1");
        System.out.println(jedis.get("num"));
        jedis.decr("num");
        System.out.println(jedis.get("num"));
        jedis.incr("num");
        jedis.incr("num");
        System.out.println(jedis.get("num"));
    }
    @Test
    //Add / subtract a number
    //incrBy returns the modified value. If the original value is a string but not a number, an exception will be thrown
    public void fun3(){
        Long num = jedis.incrBy("num", 3);
        System.out.println(num);
        jedis.decrBy("num",10);

        System.out.println(jedis.get("num"));
        jedis.set("name","caopengfei");
        //jedis.decrBy("name",1);
    }
    @Test
    //String splicing
    public void fun4(){
        Long len = jedis.append("name", "123");
        System.out.println(len);
        System.out.println(jedis.get("name"));
    }
}

Hash test

public class HashTest {
    public Jedis jedis = JedisPoolUtil.getJedis();

    //hash operates on map objects
//Information suitable for storing key value objects
    @Test
    //Save value parameter name of the first variable, map key name (key), map key value (value)
//Call hset
    public void fun() {
        Long num = jedis.hset("hash1", "username", "caopengfei");
        System.out.println(num);
        String hget = jedis.hget("hash1", "username");
        System.out.println(hget);
    }

    @Test
    //You can also save multiple key s
//Call hmset
    public void fun1() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", "caopengfei");
        map.put("age", "25");
        map.put("sex", "male");
        String res = jedis.hmset("hash2", map);
        System.out.println(res);//ok
    }

    @Test
    //Get all the values in the hash
    public void fun2() {
        Map<String, String> map2 = new HashMap<String, String>();
        map2 = jedis.hgetAll("hash2");
        System.out.println(map2);
    }

    @Test
//To delete a key in a hash, you can delete one or more keys, and the number of deleted keys is returned
    public void fun3() {
        Long num = jedis.hdel("hash2", "username", "age");
        System.out.println(num);
        Map<String, String> map2 = new HashMap<String, String>();
        map2 = jedis.hgetAll("hash2");
        System.out.println(map2);
    }

    @Test
    //Increase key value pairs in hash
    public void fun4() {
        Map<String, String> map2 = new HashMap<String, String>();
        map2 = jedis.hgetAll("hash2");
        System.out.println(map2);
        jedis.hincrBy("hash2", "age", 10);
        map2 = jedis.hgetAll("hash2");
        System.out.println(map2);
    }

    @Test
    //Determine whether a value exists in the hash
    public void fun5() {
        System.out.println(jedis.hexists("hash2", "username"));
        System.out.println(jedis.hexists("hash2", "age"));
    }

    @Test
    //Get the number of key value pairs in hash
    public void fun6() {
        System.out.println(jedis.hlen("hash2"));
    }

    //Get all key values in a hash
    @Test
    public void fun7() {
        Set<String> hash2 = jedis.hkeys("hash2");
        System.out.println(hash2);
    }

    //Get all value values
    @Test
    public void fun8() {
        List<String> hash2 = jedis.hvals("hash2");
        System.out.println(hash2);
    }
}

List test

public void testList()
{
    jedis.flushDB();
    System.out.println("===========Add one list===========");
    jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
    jedis.lpush("collections", "HashSet");
    jedis.lpush("collections", "TreeSet");
    jedis.lpush("collections", "TreeMap");
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));//-1 for the last element, - 2 for the last element
    System.out.println("collections Interval 0-3 Elements:"+jedis.lrange("collections",0,3));
    System.out.println("===============================");
    //Delete the value specified in the list. The second parameter is the number of deletions (if there are duplicates), and then the value in add will be deleted first, similar to the value out of stack
    System.out.println("Delete the specified number of elements:"+jedis.lrem("collections", 2, "HashMap"));
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
    System.out.println("Delete the following table 0-3 Elements outside the interval:"+jedis.ltrim("collections", 0, 3));
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
    System.out.println("collections List stack (left side):"+jedis.lpop("collections"));
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
    System.out.println("collections Add elements, from the right end of the list, and lpush Correspondingly:"+jedis.rpush("collections", "EnumMap"));
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
    System.out.println("collections List stack (right side):"+jedis.rpop("collections"));
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
    System.out.println("modify collections Specify the contents of subscript 1:"+jedis.lset("collections", 1, "LinkedArrayList"));
    System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));
    System.out.println("===============================");
    System.out.println("collections Length:"+jedis.llen("collections"));
    System.out.println("Obtain collections Element with subscript 2:"+jedis.lindex("collections", 2));
    System.out.println("===============================");
    jedis.lpush("sortedList", "3","6","2","0","7","4");
    System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1));
    System.out.println(jedis.sort("sortedList"));
    System.out.println("sortedList After sorting:"+jedis.lrange("sortedList", 0, -1));
}

Set test

/*
* Set The difference between a collection and a List class is
* set No duplicate data in
* He can conduct polymerization with high efficiency
* The rest of the operation is basically the same as list
*
* */
public class SetTest {
    public  Jedis jedis = JedisPoolUtil.getJedis();

    @Test
    /*Add elementsremove element*/
    public void fun(){
        Long num = jedis.sadd("myset", "a", "a", "b","abc");
        System.out.println(num);

    }
    @Test
    /*Acquire elements*/
    public void fun1(){
        Set<String> myset = jedis.smembers("myset");
        System.out.println(myset);
    }
    @Test
    /*Removing Elements*/
    public void fun2(){
        jedis.srem("myset","a","b");
        Set<String> myset = jedis.smembers("myset");
        System.out.println(myset);
    }
    @Test
    //Determine whether there is a value in this set
    public void fun3(){
        Boolean sismember = jedis.sismember("myset", "a");
        System.out.println(sismember);
    }
    @Test
    //Get A-B get difference set
    public void fun4(){
        jedis.sadd("myset1","123","32","abc","def","123456","sdfasd");
        jedis.sadd("myset2","abc","345","123","fda");
        Set<String> sdiff = jedis.sdiff("myset1", "myset2");
        System.out.println(sdiff);
    }
    @Test
    //Get intersection
    public void fun5(){
        Set<String> sinter = jedis.sinter("myset1", "myset2");
        System.out.println(sinter);

    }
    @Test
//Get and set
    public void fun6(){
        Set<String> sunion = jedis.sunion("myset1", "myset2");
        System.out.println(sunion);
    }
    @Test
//Number of members
    public void fun7(){
        System.out.println(jedis.scard("myset1"));
    }
    @Test
//Get a random member
    public void fun8(){
        System.out.println(jedis.srandmember("myset1"));
    }
    @Test
//Put the members of phase difference into a new set, and the homomorphic intersection and union can be followed by both
//Add a store
//And return the new length
    public void fun9(){
        System.out.println(jedis.sdiffstore("myset3","myset1","myset2"));
        System.out.println(jedis.smembers("myset3"));
    }
}

SortedSet test

/*
Very similar to set, they are a set of strings without duplicate data
 The difference is that each member of sortedset has a score associated with it
,redis It's the scores that sort the members of a collection from small to large
sortedset The data in must be single, but its score can be repeated
 */
public class SortedsetTest {
    public  Jedis jedis = JedisPoolUtil.getJedis();
//Add element
    @Test
    public void fun(){
        jedis.zadd("mysort",100.0, "zhangsan");
        jedis.zadd("mysort",200.0,"lisi");
        jedis.zadd("mysort",50.0,"wangwu");
        Map<String ,Double>map = new HashMap<String ,Double>();
        map.put("mutouliu",70.0);

        jedis.zadd("mysort",map);
        Set<String> mysort = jedis.zrange("mysort", 0, -1);
        System.out.println(mysort);
        Set<String> mysort1 = jedis.zrange("mysort", 1, 2);
        System.out.println(mysort1);
    }
} 

Source: https://mp.weixin.qq.com/s/kmAEk_H6UkP8ipCfDXbTJA

Posted by Rushyo on Sat, 28 Dec 2019 09:10:58 -0800