Redis Database Operation __ Database

Source: Internet
Author: User
Tags naming convention
Link Redis Database
Package Com.ithiema.jedis;

Import Org.junit.Test;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig; public class Jedistest {//Access Redis database via Java program @Test//Get a single Jedis object operations database public void Test1 () {/

        /1, get the Connection object Jedis Jedis = new Jedis ("192.168.186.131", 6379);
        2, obtain data String username = jedis.get ("username");

        SYSTEM.OUT.PRINTLN (username);
        3, Storage jedis.set ("addr", "Beijing");


    System.out.println (Jedis.get ("addr")); ///Get Jedis Connection object @Test public void Test2 () {//0, create Pool Configuration object Jedispoolconfig Poolcon by Jedis Pool
        Fig = new Jedispoolconfig ();

        Poolconfig.setmaxidle (30);//MAX idle number Poolconfig.setminidle (10);//Minimum idle number poolconfig.setmaxtotal (50);//maximum number of connections

        1, create a redis connection pool Jedispool = new Jedispool (poolconfig, "192.168.186.131", 6379); 2, from the pool to obtain Redis connection resources Jedis Jedis= Pool.getresource ();
        3, Operation database Jedis.set ("xxx", "yyyy");

        System.out.println (jedis.get ("xxx"));
        4, close the resource jedis.close ();

    Pool.close ();
 }


}

Tools Class

Package Com.ithiema.jedis;
Import java.io.IOException;
Import Java.io.InputStream;

Import java.util.Properties;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig;

    public class Jedispoolutils {private static Jedispool pool = null; static{//Load configuration file InputStream in = JedisPoolUtils.class.getClassLoader (). getResourceAsStream ("Redis.proper
        Ties ");
        Properties Pro = new properties ();
        try {pro.load (in);
        catch (IOException e) {e.printstacktrace ();
        //Get the Pool object jedispoolconfig poolconfig = new Jedispoolconfig (); Poolconfig.setmaxidle (Integer.parseint (Pro.get ("Redis.maxidle"). toString ());//MAX idle number Poolconfig.setminidle ( Integer.parseint (Pro.get ("Redis.minidle"). toString ());//Minimum idle number poolconfig.setmaxtotal (Integer.parseint (pro.get ("Redis.maxtotal"). toString ());//maximum number of connections pool = new Jedispool (Poolconfig,Pro.getproperty ("Redis.url"), Integer.parseint (Pro.get ("Redis.port"). toString ());
    The method of obtaining Jedis resources public static Jedis Getjedis () {return pool.getresource ();
        public static void Main (string[] args) {Jedis Jedis = Getjedis ();
    System.out.println (jedis.get ("xxx"));
 }




}

The configuration file is as follows

redis.maxidle=30
redis.minidle=10
redis.maxtotal=100
redis.url=192.168.186.131
redis.port=6379

The jar packages you need to use are as follows
Redis Data Type

Redis is an advanced key-value storage system.
The key is a string type, as much as the following points are met:
1 key not too long, it is best not to operate 1024 bytes, which will not only consume memory but also reduce the search efficiency
2 Key not too short, if too short will reduce key readability
3 in the project, the key is best to have a uniform naming convention (according to the needs of the enterprise)
Where value supports five types of data:
1 Strings String
2) string list lists
3) String Collection sets
4) Ordered string collection sorted sets
5) hash type HASHS store string


1 Set key value: The SET key holds the specified string value and overwrites if the key exists. Always return "OK"
2 Get key: Gets the value of the key. If the value associated with this key is not a string type, Redis returns an error message because the GET command can only be used to obtain string value, or null if the key does not exist.

3 Getset Key value: Gets the value of the key first, and then sets the value of the key.

4 incr key: Increments the value atomicity of the specified key by 1. If the key does not exist, its initial value is 0, and the value is 1 after incr. If value cannot be converted to an integral type, such as Hello, the operation will fail and return the appropriate error message.
5 DECR key: decrements the value atomicity of the specified key by 1. If the key does not exist, its initial value is 0, and after incr its value is-1. If value cannot be converted to an integral type, such as Hello, the operation will fail and return the appropriate error message.

6) Incrby key increment: Adds the value atomicity of the specified key increment, if the key does not exist, the initial value is 0, after Incrby, the value is increment. If the value cannot be converted to an integral type, such as Hello fails and an error message is returned
7 Decrby Key Decrement: Reduces the value atomicity of the specified key decrement, if the key does not exist, the initial value is 0, after Decrby, the value is decrement. If the value cannot be converted to an integral type, such as Hello fails and an error message is returned

8 Append key value: If the key exists, append the value after the original value, or recreate a key/value if the key does not exist

Storage Lists Type

1) lpush key value1 value2 ... : Inserts all values in the head of the list associated with the specified key, if the key does not exist, creates an empty list associated with the key before inserting it, and then inserts data into the list's head. The insert succeeds, returning the number of elements.
2) Rpush key value1, value2 ... : Add elements at the end of the list
3) Lrange key start: Gets the value of the element from start to end in the list, and the start, ends can be negative, if 1 is the element at the end of the list,-2 is the penultimate, and so on ...

4) Lpushx Key value: Inserts value at the head of the list associated with the specified key only if the key specified in the parameter exists (if the key is not present in the list that is managed by the key).
5) Rpushx key value: adding elements at the end of the list

6) Lpop key: Returns and pops the first element in the linked list associated with the specified key, that is, the head element.
7 rpop key: Eject element from tail.

8) Rpoplpush Resource destination: The tail element in the linked list is ejected and added to the head

9 Llen Key: Returns the number of elements in the linked list associated with the specified key.

LSet Key Index value: Sets the element value of the index in the linked list, 0 represents the header element of the list, and 1 represents the tail element of the list.

Lrem Key count value: Deletes the element with the count value, and if count is greater than 0, traverses and deletes the element with the count value of value, if count is less than 0, and then traverses and deletes from the tail head. If count is equal to 0, all elements equal to value in the linked list are deleted.

Linsert key Before|after Pivot Value: Inserts the value element before or after the pivot element.
Storage Sets Type

In Redis, we can look at a set type as an unordered character set, and like the list type, we can also perform actions such as adding, deleting, or determining whether an element exists on that type of data value. It should be explained that the time of these operations is constant time. The maximum number of elements set can contain is 4294967295.
Unlike the list type, duplicate elements are not allowed in the set collection. In contrast to the list type, the set type has functionally a very important feature, namely, the aggregation calculation operations between multiple sets on the server side, such as unions, intersections, and differences. Because these operations are done on the server side, they are extremely efficient and also save a large amount of network IO overhead

1) sadd key value1, value2 ... : Adds data to set, if the value of the key is already there, it is not added repeatedly
2) smembers key: Gets all members of the set
3) SCard key: Gets the number of members in the set

4) Sismember Key member: Determines whether the members specified in the parameter are in the set, 1 indicates existence, 0 indicates that it does not exist, or that the key itself does not exist
5) Srem key member1, member2 ... : Deletes the member specified in the set

6) Srandmember key: Randomly returns a member of a set

7) Sdiff Sdiff key1 Key2: Returns a member of the difference between Key1 and Key2, and is related to the order of the key. That is, the difference set is returned.

8) Sdiffstore Destination Key1 key2: Storing Key1, Key2-difference members on destination

9) sinter Key[key1,key2 ...] : Returns the intersection.
10) Sinterstore Destination Key1 Key2: Storing the returned intersection on destination


11) sunion Key1, Key2: Return and set.

12) Sunionstore Destination Key1 Key2: Storing the returned collection on destination
4. Storage SortedSet


Sorted-sets and sets types are very similar, and they are all collections of strings that do not allow duplicate members to appear in a set. The main difference between them is that each member of the sorted-sets will have a fraction (score) associated with it, and Redis is the sort of small to large members of the set through fractions. However, it is important to note that although the members in the Sorted-sets must be unique, the score (score) can be repeated.
Adding, deleting, or updating a member in Sorted-set is a very fast operation with a time complexity of the logarithm of the number of members in the collection. Because the members in the Sorted-sets are in an orderly position in the collection, even accessing the members in the middle of the collection is still very efficient. In fact, this feature of Redis is difficult to implement in many other types of databases, in other words, it is very difficult to model in other databases to achieve the same efficiency as Redis.

1) Zadd key score member Score2 Member2 ... : Store all members and the members ' scores in Sorted-set
2) Zcard key: Gets the number of members in the collection

3) zcount Key min Max: The member that gets the score between [Min,max]
zincrby Key Increment member: Sets the increased score for the specified members.
zrange key start [Withscores]: Gets the member whose PIN is start-end in the collection, and the [withscores] parameter indicates that the returned member contains its score.
zrangebyscore key min Max [withscores] [limit offset count]: Returns a fraction of the members in [Min,max] and sorts them by fractions from low to high. [Withscores]: Displays the score; [Limit offset count]:offset indicates that the element marked with offset starts and returns the Count member.
zrank Key member: Returns the location of the members in the collection.
zrem key Member[member ...] : Removes the specified member from the collection and can specify more than one member.
zscore Key member: Returns the score of 5 for the specified members . Store Hash

The hashes type in Redis can be viewed as a map container with string key and string value. So this type is ideal for storing information about a value object. such as username, password and age. If the hash contains few fields, the data of that type will take up only a small amount of disk space. Each hash can store 4,294,967,295 key-value pairs.

1 hset key field value: Sets the Field/value pair (key-value pair) for the specified key
2 Hgetall key: Get all filed-vaule in key

3) hget key field: Returns the value of field in the specified key

4) hmset key fields: Set multiple Filed/value in key

5) hmget key fileds: Gets the values of multiple filed in the key
6) hexists key field: Determine if the filed exists in the specified key
7) Hlen key: Gets the number of field that the key contains
8) Hincrby key field increment: Set the value of filed in key to increase increment, such as: Age increased by 20

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.