当前位置:网站首页>Redis - basic use (key, string, list, set, Zset, hash, geo, bitmap, hyperloglog, transaction)

Redis - basic use (key, string, list, set, Zset, hash, geo, bitmap, hyperloglog, transaction)

2022-07-07 21:33:00 m0_ sixty-three million five hundred and forty-four thousand on

Redis Chinese net https://www.redis.net.cn/

1. summary

1.1 What is? NoSQL

1.2 NoSQL Four categories

1.3  3V+3 high

1.4 Redis summary

Remote Dictionary Server —— Remote dictionary service

2. Installation and start up (Linux)

2.1 download

1. download

download redis-6.0.6.tar.gz To /usr/local/src Catalog

2. decompression

tar -zxvf redis-6.0.6.tar.gz

3. Entry directory

cd /usr/local/src/redis-6.0.6

4、 Basic environment installation

yum install -y gcc tcl

make

make install

2.2. Modify the configuration file

myconfig->redis.conf

 

2.3 start-up

1. Enter the installation directory

cd /usr/local/bin

2. Specify that the configuration file is turned on

redis-server myconfig/redis.conf

3. Common command

redis Command manuals https://www.redis.net.cn/order/


3.1 Server command

command describe
Redis Flushdb command Delete all... Of the current database key
Redis Flushall command Delete all... Of all databases key
Redis Dbsize command Returns the... Of the current database key The number of
Redis Shutdown command Asynchronously save data to hard disk , And shut down the server
Redis Client Kill command Close the client connection

3.2 Connection command

command describe
Redis Echo command Print string
Redis Select command Switch to the specified database
Redis Ping command See if the service is running
Redis Quit command Close the current connection
Redis Auth command Verify that the password is correct

3.3 key command

command describe
Redis Type command return key The type of value stored .
Redis PEXPIREAT command Set up key In milliseconds .
Redis PEXPIREAT command Set up key Time stamp of expiration time (unix timestamp) In milliseconds
Redis Rename command modify key The name of
Redis PERSIST command remove key The expiration time of ,key Will last .
Redis Move command Will be the current database of key Move to a given database db among .
Redis DEL command This command is used in key Existence is deletion key.
Redis Renamenx command Only when the newkey When there is no , take key Renamed as newkey .
Redis EXISTS command Check the given key Whether there is .
Redis Keys command Find all that match the given pattern ( pattern) Of key .

3.4 Common data types

3.4.1 String

command describe
Redis Setnx command Only in key Set when not present key Value .
Redis Getrange command return key The child character of the string value in
Redis Mset command Set one or more... At the same time key-value Yes .
Redis Setex command Will value value Related to key , And will key The expiration time of is set to seconds ( In seconds ).
Redis SET command Set the specified key Value
Redis Get command Get specified key Value .
Redis Decr command take key Subtract one from the number stored in .
Redis Decrby command key The stored value minus the given decrement value (decrement) .
Redis Strlen command return key The length of the stored string value .
Redis Msetnx command Set one or more... At the same time key-value Yes , If and only if all given key It doesn't exist .
Redis Incrby command take key The stored value plus the given increment value (increment) .
Redis Incrbyfloat command take key The stored value plus the given floating-point delta value (increment) .
Redis Setrange command use value Parameter override given key String value stored , From the offset offset Start .
Redis Psetex command This command and SETEX Command similar , But it's set in milliseconds key Survival time , Not like it SETEX Order that , In seconds .
Redis Append command If key Already exists and is a string , APPEND The order will value Append to key The end of the original value .
Redis Getset command Will be given key The value of the set value , And back to key The old value (old value).
Redis Mget command Get all ( One or more ) Given key Value .
Redis Incr command take key The value of the number stored in is increased by one .

3.4.2 Hash

command describe
Redis Hmset command There will be more than one field-value ( Domain - value ) Set to hash table key in .
Redis Hmget command Get the value of all the given fields
Redis Hset command Hash table key In the field field The value of the set value .
Redis Hgetall command Gets the specified in the hash table key All fields and values of
Redis Hget command Gets the value of the specified field stored in the hash table /td>
Redis Hexists command Look at the hash table key in , Whether the specified field exists .
Redis Hincrby command Hash table key The integer value of the specified field in plus the increment increment .
Redis Hlen command Get the number of fields in the hash table
Redis Hdel command Delete one or more hash table fields
Redis Hvals command Get all values in hash table
Redis Hincrbyfloat command Hash table key The floating-point value of the specified field in plus the increment increment .
Redis Hkeys command Get all the fields in the hash table
Redis Hsetnx command Only in the fields field When there is no , Set the value of the hash table field .

3.4.3 List

command describe
Redis Lindex command Get the elements in the list by index
Redis Rpush command Add one or more values... To the list
Redis Lrange command Get the elements in the specified range of the list
Redis Rpoplpush command Remove the last element of the list , And add the element to another list and return
Redis Blpop command Move out and get the first element of the list , If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .
Redis Brpop command Move out and get the last element of the list , If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .
Redis Brpoplpush command Pop up a value... From the list , Insert the pop-up element into another list and return it ; If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .
Redis Lrem command Remove list elements
Redis Llen command Get list length
Redis Ltrim command Trim a list (trim), That is to say , Let the list keep only the elements in the specified range , Elements that are not in the specified range will be removed .
Redis Lpop command Move out and get the first element of the list
Redis Lpushx command Insert one or more values into the existing list header
Redis Linsert command Insert an element before or after a list element
Redis Rpop command Remove and get the last element of the list
Redis Lset command Set the value of the list element through the index
Redis Lpush command Insert one or more values into the list header
Redis Rpushx command Add value to existing list

3.4.4 Set

command describe
Redis Sunion command Returns the union of all given sets
Redis Scard command Get the number of members of the collection
Redis Srandmember command Returns one or more random numbers in a set
Redis Smembers command Returns all members of the collection
Redis Sinter command Returns the intersection of a given set
Redis Srem command Remove one or more members of the collection
Redis Smove command take member Elements from source The assembly moves to destination aggregate
Redis Sadd command Add one or more members to the collection
Redis Sismember command Judge member Is the element a collection key Members of
Redis Sdiffstore command Returns the difference set of a given set and stores it in destination in
Redis Sdiff command Returns the difference set of all given sets
Redis Sscan command Iterate over the elements in the collection
Redis Sinterstore command Returns the intersection of a given set and stores it in destination in
Redis Sunionstore command The union of all given sets is stored in destination Collection
Redis Spop command Remove and return a random element from the collection

3.4.5 zset ( Ordered set )

command describe
Redis Zrevrank command Returns the rank of a specified member in an ordered set , Members of an ordered set are decremented by fractions ( From big to small ) Sort
Redis Zlexcount command Computes the number of members in the specified dictionary interval in an ordered collection
Redis Zunionstore command Computes the union of a given ordered set or sets , And store it in the new key in
Redis Zremrangebyrank command Remove all members of a given rank range from an ordered set
Redis Zcard command Get the number of members of the ordered set
Redis Zrem command Remove one or more members of an ordered collection
Redis Zinterstore command Calculates the intersection of a given ordered set or sets and stores the result set in a new ordered set key in
Redis Zrank command Returns the index of a specified member in an ordered collection
Redis Zincrby command Add the increment... To the score of the specified member in the ordered set increment
Redis Zrangebyscore command Returns the members of an ordered set in a specified interval through scores
Redis Zrangebylex command Returns the members of an ordered set through a dictionary interval
Redis Zscore command Back to the ordered set , The score of a member
Redis Zremrangebyscore command Remove all members of a given fraction interval from an ordered set
Redis Zscan command Iterate over elements in an ordered set ( Include element members and element scores )
Redis Zrevrangebyscore command Returns the members of the specified score range in an ordered set , Rank scores from high to low
Redis Zremrangebylex command Remove all members of a given dictionary interval from an ordered set
Redis Zrevrange command Returns the members of a specified interval in an ordered set , Through the index , Score from high to the end
Redis Zrange command Returns an ordered set through an index interval to synthesize members in a specified interval
Redis Zcount command Calculates the number of members of a specified interval fraction in an ordered set
Redis Zadd command Add one or more members... To an ordered collection , Or update scores of existing members

3.5 Special data types

3.5.1 HyperLogLog

command describe
Redis Pgmerge command Will be multiple HyperLogLog Merge into one HyperLogLog
Redis Pfadd command Add specified elements to HyperLogLog in .
Redis Pfcount command Return to a given HyperLogLog The base estimate of .

3.5.2 geo

command describe
Redis GEOHASH command Returns the... Of one or more positional elements Geohash Express
Redis GEOPOS command from key Returns the location of all the positioning elements ( Longitude and latitude )
Redis GEODIST command Returns the distance between two given positions
Redis GEORADIUS command Centered on a given latitude and longitude , Find the elements in a certain radius
Redis GEOADD command Geospatial location to be specified ( latitude 、 longitude 、 name ) Add to specified key in
Redis GEORADIUSBYMEMBER command Find the elements in the specified range , The center point is determined by a given location element

3.5.3 bitmap

getbit command Yes key String value stored , Gets the bit on the specified offset (bit).
getbit command Yes key String value stored , Sets or clears the bit on the specified offset (bit).bitcount
bitcount Statistics 1 The number of
bitcount Statistics 1 The number of
bitcount Statistics 1 The number of

4. Business

4.1 multi&exec

 

4.2 watch treat as redis Optimistic lock operation of

5.Jedis

5.1 Connect redis

1. Induced dependence

    <dependencies>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.2.3</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.36</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

2.  Connect remote redis

public class TestPing {
    public static void main(String[] args) {
        String host = "192.168.59.128";
        int port = 6379;
        Jedis jedis = new Jedis(host, port);
        System.out.println(jedis.ping());
    }
}

5.2 common API

5.2.1 key

import redis.clients.jedis.Jedis;

import java.util.Set;

public class TestKey {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        jedis.set("username", "zhangsan");
        jedis.set("age", "30");
        jedis.set("address", "beijing");
        System.out.println("===================================================");

        Set<String> keys = jedis.keys("*");// Get all keys 
        System.out.println(keys);//[age, username, address]

        boolean exists = jedis.exists("username");// Judge whether the key exists 
        System.out.println(exists);//true

        String type = jedis.type("username");// The data type of the key 
        System.out.println(type);//string

        String key = jedis.randomKey();// Returns a key at random 
        System.out.println(key);//username

        jedis.rename("username", "name");// Change key name 
        System.out.println(jedis.get("name"));//zhangsan

        long size = jedis.dbSize();//key Number of 
        System.out.println(size);//3

        jedis.set("hello","world");
        System.out.println(jedis.get("hello"));
        jedis.pexpireAt("hello", 60);// Set the expiration time ???????
        System.out.println(jedis.get("hello"));
    }
}

5.2.2 String


import redis.clients.jedis.Jedis;

public class TestString {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        jedis.set("username", "zhangsan");
        jedis.mset("password", "123", "age", "30", "hobby", "swim");// Set key value pairs in batch 
        System.out.println(jedis.get("username"));//zhangsan
        System.out.println(jedis.mget("username", "age", "password"));// Batch fetch value   [zhangsan, 30, 123]
        jedis.setnx("username", "lisi");// The new key value pair prevents the original value from being overridden 
        System.out.println(jedis.get("username"));//zhangsan123
        jedis.setnx("address", "beijing");
        System.out.println(jedis.get("address"));//beijing
        jedis.setex("color", 60, "red");// Add a key value pair and set the effective time 


        jedis.del("hobby");// Delete... According to the key 
        System.out.println(jedis.get("hobby"));//null

        jedis.append("username", "123");// String splicing 
        System.out.println(jedis.get("username"));//zhangsan123

        String age = jedis.getSet("age", "20");// Will be given key The value of the set value, And back to key The old value (old value).
        System.out.println(age);//30
        System.out.println(jedis.get("age"));//20

        jedis.set("num", "0");
        jedis.incr("num");// take key Increase the value of the number stored in 1.
        System.out.println(jedis.get("num"));//1
        jedis.incrBy("num", 3);// take key The value of the number stored in plus 3.
        System.out.println(jedis.get("num"));//4
        jedis.decr("num");// take key The number stored in minus 1.
        System.out.println(jedis.get("num"));//3
        jedis.decrBy("num", 2);// take key The number stored in minus 2.
        System.out.println(jedis.get("num"));//1

        String getrange = jedis.getrange("username", 2, 4);// Intercepting string 
        System.out.println(getrange);//zhangsan123 -> ang
        long setrange = jedis.setrange("username", 5, "si");// String specifies position substitution 
        System.out.println(setrange);//11
        System.out.println(jedis.get("username"));//zhangsan123 -> zhangsin123

        jedis.close();
    }
}

5.2.3 List

import redis.clients.jedis.Jedis;

public class TestList {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        jedis.lpush("color", "red");// Stack from the left 
        jedis.lpush("color", "blue");
        jedis.lpush("color", "yellow");
        jedis.lpush("color", "green");
        jedis.lpush("color", "green");
        System.out.println(jedis.lrange("color", 0, -1));//[green, green, yellow, blue, red]
        System.out.println(jedis.lrange("color", 0, 2));//[green, green, yellow]
        jedis.rpush("color", "red");// Stack from the right 
        jedis.rpush("color", "blue");
        jedis.rpush("color", "yellow");
        jedis.rpush("color", "green");
        jedis.rpush("color", "green");
        System.out.println(jedis.lrange("color", 0, -1));
        //[green, green, yellow, blue, red, red, blue, yellow, green, green]

        jedis.lrem("color", 3, "green");// Remove the specified number of elements 
        System.out.println(jedis.lrange("color", 0, -1));//[yellow, blue, red, red, blue, yellow, green]
        jedis.lrem("color", 2, "red");// Remove the specified number of elements 
        System.out.println(jedis.lrange("color", 0, -1));//[yellow, blue, blue, yellow, green]

        String color = jedis.lindex("color", 3);// Gets the element of the specified subscript 
        System.out.println(color);//yellow

        jedis.ltrim("color",1,3);// Truncate the subscript to 1 To 3 The elements of 
        System.out.println(jedis.lrange("color", 0, -1));//[blue, blue, yellow]

        jedis.lpop("color");// Out of the stack from the left 
        System.out.println(jedis.lrange("color", 0, -1));//[blue, yellow]
        jedis.rpop("color");// Get out of the stack from the right 
        System.out.println(jedis.lrange("color", 0, -1));//[blue]

        jedis.close();
    }
}

5.2.4 Set

import redis.clients.jedis.Jedis;

import java.util.Set;

public class TestSet {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        jedis.sadd("color", "red");// Add elements to the collection ( No repetition )
        jedis.sadd("color", "blue");
        jedis.sadd("color", "yellow");
        jedis.sadd("color", "green");
        jedis.sadd("color", "green");
        System.out.println(jedis.smembers("color"));//[yellow, red, blue, green]

        jedis.srem("color","green");// Deletes the specified element 
        System.out.println(jedis.smembers("color"));//[blue, red, yellow]

        boolean sismember = jedis.sismember("color", "green");// Determine whether an element is included in the collection 
        boolean sismember1 = jedis.sismember("color", "blue");
        System.out.println(sismember);//false
        System.out.println(sismember1);//true

        long color = jedis.scard("color");// The number of elements in the collection 
        System.out.println(color);//3

        System.out.println(jedis.smembers("color"));//[red, blue, yellow]
        System.out.println(jedis.smembers("color2"));//[]
        jedis.smove("color","color2","red");// Move an element to the specified collection 
        System.out.println(jedis.smembers("color"));//[blue, yellow]
        System.out.println(jedis.smembers("color2"));//[red]

        jedis.spop("color");// Remove elements at random 
        System.out.println(jedis.smembers("color"));//[blue]

        jedis.flushDB();
        jedis.sadd("color1","red","blue","yellow");
        jedis.sadd("color2","red","green");
        Set<String> sinter = jedis.sinter("color1", "color2");// intersection 
        System.out.println(sinter);//[red]
        Set<String> sunion = jedis.sunion("color1", "color2");// Combine 
        System.out.println(sunion);//[red, yellow, blue, green]
        Set<String> sdiff1 = jedis.sdiff("color1", "color2");// Difference set 
        Set<String> sdiff2 = jedis.sdiff("color2", "color1");// Difference set 
        System.out.println(sdiff1);//[yellow, blue]
        System.out.println(sdiff2);//[green]

        jedis.close();
    }
}

5.2.5 Zset

import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;

import java.util.List;

public class TestZset {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        jedis.zadd("salary",3000,"zhangsan");// Additive elements : The weight + Content 
        jedis.zadd("salary",2500,"lisi");
        jedis.zadd("salary",1500,"wangwu");

        List<String> zrangeByScore1 = jedis.zrangeByScore("salary", "-inf", "+inf");// All elements are arranged from small to large 
        System.out.println(zrangeByScore1);//[wangwu, lisi, zhangsan]
        List<String> zrevrangeByScore1 = jedis.zrevrangeByScore("salary", "+inf", "-inf");// All elements are arranged from small to large 
        System.out.println(zrevrangeByScore1);//[zhangsan, lisi, wangwu]

        // All elements are arranged from small to large with grades 
        List<Tuple> salary1 = jedis.zrangeByScoreWithScores("salary", "-inf", "+inf");
        System.out.println(salary1);//[[wangwu,1500.0], [lisi,2500.0], [zhangsan,3000.0]]
        // All elements are arranged from large to small with grades 
        List<Tuple> salary2 = jedis.zrevrangeByScoreWithScores("salary", "+inf", "-inf");
        System.out.println(salary2);//[[zhangsan,3000.0], [lisi,2500.0], [wangwu,1500.0]]

        List<String> zrangeByScore2 = jedis.zrangeByScore("salary", "2000", "4000");// Specify the arrangement of interval elements from small to large 
        System.out.println(zrangeByScore2);//[lisi, zhangsan]
        List<String> zrevrangeByScore2 = jedis.zrevrangeByScore("salary", 4000, 2000);// Specify the arrangement of interval elements from large to small 
        System.out.println(zrevrangeByScore2);//[zhangsan, lisi]

        List<String> zrevrang = jedis.zrevrange("salary", 0, -1);// All elements are arranged from large to small 
        System.out.println(zrevrang);//[zhangsan, lisi, wangwu]


        long zcard = jedis.zcard("salary");// Get the number of all elements 
        System.out.println(zcard);//3
        long zcount = jedis.zcount("salary", 1000, 2000);// Gets the number of elements in the specified interval 
        System.out.println(zcount);//1

        jedis.zrem("salary", "lisi");// Removes the specified element 
        System.out.println(jedis.zrangeByScoreWithScores("salary", "-inf", "+inf"));//[[wangwu,1500.0], [zhangsan,3000.0]]

        jedis.close();
    }
}

5.2.6 Hash

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TestHash {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        Map<String, String> map = new HashMap<String, String>();
        map.put("key2","value2");
        map.put("key3","value3");
        map.put("key4","value4");

        jedis.hset("hash","key1","key1");// Add a single element 
        jedis.hmset("hash",map);// Add multiple elements 

        String hget = jedis.hget("hash", "key3");// Get a single value 
        System.out.println(hget);//value3
        List<String> hmget = jedis.hmget("hash", "key2", "key3");// Get multiple values 
        System.out.println(hmget);//[value2, value3]

        Set<String> hkeys = jedis.hkeys("hash");// Get all keys 
        System.out.println(hkeys);//[key1, key2, key3, key4]
        List<String> hvals = jedis.hvals("hash");// Get all values 
        System.out.println(hvals);//[key1, value2, value3, value4]
        Map<String, String> hgetAll = jedis.hgetAll("hash");// Get all key value pairs 
        System.out.println(hgetAll);//{key1=key1, key2=value2, key3=value3, key4=value4}

        long hlen = jedis.hlen("hash");// The number of key-value pairs 
        System.out.println(hlen);//4

        boolean hexists = jedis.hexists("hash", "key2");// Judge whether the key exists 
        System.out.println(hexists);//true

        jedis.hincrBy("hash","key5",5);// Specify increment , Add... If not 
        System.out.println(jedis.hgetAll("hash"));//{key1=key1, key2=value2, key5=5, key3=value3, key4=value4}
        jedis.hincrBy("hash","key5",3);
        System.out.println(jedis.hgetAll("hash"));//{key1=key1, key2=value2, key5=8, key3=value3, key4=value4}

        jedis.close();
    }
}

5.2.7 geo

import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.args.GeoUnit;
import redis.clients.jedis.params.GeoRadiusParam;
import redis.clients.jedis.resps.GeoRadiusResponse;

import java.util.List;

public class TestGeo {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");


        /**
         * geoadd  Add location 
          The rules : Two levels cannot be added directly , We usually download city data , Directly through java The program is imported once !
          Effective longitude from -180 C to 180 degree .
          The latitude of effect is from -85.05112878 C to 85.05112878 degree .
          When the coordinate position exceeds the specified range above , The command will return an error .
         */
        jedis.geoadd("city", 116.40, 39.90, "beijing");
        jedis.geoadd("city", 121.47, 31.23, "shanghai");
        jedis.geoadd("city", 106.50, 29.53, "chongqing");
        jedis.geoadd("city", 114.05, 22.52, "shenzhen");
        jedis.geoadd("city", 120.16, 30.24, "hangzhou");
        jedis.geoadd("city", 108.96, 34.26, "xian");


        /**
         * geopos  Get the current location ( One or more ): It must be a coordinate value !
         */
        List<GeoCoordinate> chongqing = jedis.geopos("city", "chongqing");
        System.out.println(chongqing);//[(106.49999767541885,29.529999579006592)]
        List<GeoCoordinate> beijingAndXian = jedis.geopos("city", "beijing", "xian");
        System.out.println(beijingAndXian);//[(116.39999896287918,39.900000091670925), (108.96000176668167,34.2599996441893)]


        /**
         * geodist  The distance between the two places 
          Company :
         m  Expressed in meters .   Default 
         km  Expressed in kilometers .
         mi  In miles .
         ft  In feet .
         */
        Double geodist = jedis.geodist("city", "beijing", "shanghai");
        System.out.println(geodist + "m");//1067378.7564m
        Double geodist2 = jedis.geodist("city", "beijing", "shanghai", GeoUnit.KM);
        System.out.println(geodist2 + "km");//1067.3788km


        /**
         *  Get the hash value of the location 
         */
        List<String> geohash = jedis.geohash("city", "beijing", "shanghai", "shenzhen");
        System.out.println(geohash);//[wx4fbxxfke0, wtw3sj5zbj0, ws10578st80]


        /**
         * georadius    Given geographical coordinates , Gets the collection of geographic locations within the specified range 
          return :
          Match the name of the location 
          The longitude and latitude of the matching position 
          The distance between the matching location and the given geographical location 
          Sort from near to far 
          Quantity returned 
         */
        List<GeoRadiusResponse> city = jedis.georadius("city", 110, 30, 1000,
                GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withCoord().withDist().sortAscending().count(3));
        ParseGeoresponse(city);
        //chongqing—— distance :341.9374—— longitude :106.49999767541885—— latitude :29.529999579006592
        //xian—— distance :483.834—— longitude :108.96000176668167—— latitude :34.2599996441893
        //shengzhen—— distance :924.6408—— longitude :114.04999762773514—— latitude :22.520000087950386


        /**
         * georadiusByMember    According to the location , Gets the collection of geographic locations within the specified range 
          return :
          Match the name of the location 
          The longitude and latitude of the matching position 
          The distance between the matching location and the given geographical location 
          Sort from near to far 
          Quantity returned 
         */
        List<GeoRadiusResponse> city2 = jedis.georadiusByMember("city", "beijing", 1000,
                GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withCoord().withDist().sortAscending().count(2));
        ParseGeoresponse(city2);
        //beijing—— distance :0.0—— longitude :116.39999896287918—— latitude :39.900000091670925
        //xian—— distance :910.0565—— longitude :108.96000176668167—— latitude :34.2599996441893



        /**
         *  use Zset operation 
         */
        List<String> list = jedis.zrange("city", 0, -1);
        System.out.println(list);//[chongqing, xian, shenzhen, hangzhou, shanghai, beijing]
        jedis.zrem("city","xian");
        System.out.println(jedis.zrange("city",0,-1));//[chongqing, shenzhen, hangzhou, shanghai, beijing]

        jedis.close();
    }

    /**
     *  Result analysis 
     *
     * @param city
     */
    private static void ParseGeoresponse(List<GeoRadiusResponse> city) {
        for (GeoRadiusResponse geoRadiusResponse : city) {
            String cityName = geoRadiusResponse.getMemberByString();
            double distance = geoRadiusResponse.getDistance();
            double longitude = geoRadiusResponse.getCoordinate().getLongitude();
            double latitude = geoRadiusResponse.getCoordinate().getLatitude();
            System.out.println(cityName + "—— distance :" + distance + "—— longitude :" + longitude + "—— latitude :" + latitude);
        }
    }
}

5.2.8 hyperloglog

import redis.clients.jedis.Jedis;

public class TestHyperloglog {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        // Additive elements 
        jedis.pfadd("num1", "a", "b", "c", "d", "e", "a", "b");
        jedis.pfadd("num2", "f", "g", "h", "k");

        // Count non repeating elements 
        System.out.println(jedis.pfcount("num1"));//5
        System.out.println(jedis.pfcount("num2"));//4

        // take num1 and num2 The results of the merger , Put in num1 in , And count the non repeating elements 
        jedis.pfmerge("num1","num2");
        System.out.println(jedis.pfcount("num1"));//9
        System.out.println(jedis.pfcount("num2"));//4
    }
}

5.2.9 bitmap

import redis.clients.jedis.Jedis;

public class TestBitmap {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        System.out.println("===================================================");

        // Record the clock in record of a week 
        jedis.setbit("daily",0,true);
        jedis.setbit("daily",1,false);
        jedis.setbit("daily",2,false);
        jedis.setbit("daily",3,true);
        jedis.setbit("daily",4,true);
        jedis.setbit("daily",5,false);
        jedis.setbit("daily",6,true);

        boolean daily = jedis.getbit("daily", 2);// Get the clocking record of the specified day 
        System.out.println(daily);//false

        long bitcount = jedis.bitcount("daily");// Record as true The number of 
        System.out.println(bitcount);//4
        
        jedis.close();
    }
}

5.2.10  Business


import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestTransaction {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.59.128", 6379);

        jedis.select(0);// Change database 
        jedis.flushDB();// Clear the current database 
        System.out.println(jedis.dbSize());//0
        jedis.set("money", "100");
        System.out.println("===================================================");

        jedis.watch("money");// Turn on monitoring 
        Transaction multi = jedis.multi();// Open transaction 
        try {
            multi.set("name", "zhangsan");
            int i = 1 / 0;
            multi.set("age", "30");
            multi.incrBy("money", 10);
            multi.exec();// Perform transactions , It will be monitored version
        } catch (Exception e) {
            multi.discard();// Cancel the business , Will not be implemented 
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("name"));
            System.out.println(jedis.get("age"));
            System.out.println(jedis.get("money"));
            jedis.close();
        }

        //java.lang.ArithmeticException: / by zero
        //null
        //null
        //100
    }
}

原网站

版权声明
本文为[m0_ sixty-three million five hundred and forty-four thousand on]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071729461983.html