Java uses Redis
REmote DIctionary Server (Redis) is a key-value storage system written by Salvatore Sanfilippo.
Redis is an open-source log-type, Key-Value database written in ansi c language that complies with the BSD Protocol, supports the network, and can be persistent based on memory, and provides APIs in multiple languages.
It is usually called a Data Structure server, because values can be strings, maps, lists, sets) and sorted sets.
Redis has created a new way of storing data. When using Redis, we don't have to focus on how to put elephants in the refrigerator in the face of monotonous databases, instead, Redis uses flexible data structures and data operations to build different refrigerators for different elephants.
I. Common Redis Data Types
Redis has the following data types:
String
Hash
List
Set
Sorted set
Before describing these data types, let's take a look at how Redis's internal memory management describes these different data types:
First, Redis uses a redisObject object to represent all keys and values. The primary information of redisObject is shown in: type represents the specific data type of a value object, encoding is the storage method of different data types in redis. For example, if type = string indicates that value is stored as a common string, the corresponding encoding can be raw or int, if it is an int, it indicates that the actual redis instance stores and represents the string by numeric type. Of course, the premise is that the string itself can be represented by numerical values, for example: "123" "456.
Note the vm field here. This field is actually allocated only when the Redis virtual memory function is enabled. This function is disabled by default, this function will be described later. Redis uses redisObject to indicate that all key/value data is a waste of memory, of course, these memory management costs are mainly paid to provide a unified management interface for different Redis data types. The actual author also provides a variety of methods to help us minimize memory usage, we will discuss it in detail later.
Next we will analyze the usage and internal implementation of these five data types one by one:
- String
Common commands:
Set, get, decr, incr, mget, etc.
Application scenarios:
String is the most common data type. Common key/value storage can be classified as this type, so we will not explain it here.
Implementation Method:
String is a String by default stored in redis and is referenced by redisObject. When an incr, decr, or other operation is performed, it is converted to a numeric type for calculation. In this case, the encoding field of redisObject is int.
- Hash
Common commands:
Hget, hset, hgetall, etc.
Application scenarios:
Let's take an example to describe the Hash Application Scenario. For example, we want to store a user information object data that contains the following information:
The User ID is the search key. The stored value user object contains the name, age, birthday, and other information. If you use a common key/value structure for storage, there are two storage methods:
The first method is to use the user ID as the search key and encapsulate other information into an object for storage in serialized mode. The disadvantage of this method is that it increases the serialization/deserialization overhead, in addition, when you need to modify one of the items, You need to retrieve the entire object, and the modification operation needs to protect concurrency and introduce complicated problems such as CAS.
The second method is to store the key-value pair as many members of the user information object, and use the user ID + name of the corresponding attribute as a unique identifier to obtain the value of the corresponding attribute, although serialization overhead and concurrency problems are saved, the user ID is retained. If there is a large amount of such data, the memory waste is still considerable.
The Hash provided by Redis can solve this problem very well. Redis's Hash is actually a HashMap of internally stored values and provides interfaces for direct access to this Map member, such:
That is to say, the Key is still the user ID, the value is a Map, the key of the Map is the property name of the member, and the value is the property value, in this way, you can directly modify and access data through the internal Map Key (the internal Map key in Redis is called field), that is, through the key (User ID) + field (attribute tag) can operate the corresponding attribute data, neither storing data repeatedly nor causing serialization and concurrency modification control problems. Solved the problem.
At the same time, it should be noted that Redis provides an interface (hgetall) to directly retrieve all attribute data. However, if there are many internal Map members, it involves traversing the entire internal Map operation, because of the Redis single-threaded model, this traversal operation may be time-consuming, and requests from other clients do not respond at all. This requires special attention.
Implementation Method:
As mentioned above, the Value corresponding to Redis Hash is actually a HashMap. There are two different implementations here, when there are few Members of this Hash, Redis will adopt a compact storage like a one-dimensional array to save memory, instead of a real HashMap structure. The corresponding value redisObject's encoding is zipmap, when the number of members increases, it is automatically converted to a real HashMap. In this case, encoding is ht.
- List
Common commands:
Lpush, rpush, lpop, rpop, and lrange.
Application scenarios:
Redis list has many application scenarios and is also one of Redis's most important data structures. For example, the twitter follow list and fans list can all be implemented using the Redis list structure, which is easy to understand, this is not repeated here.
Implementation Method:
The implementation of Redis list is a two-way linked list, that is, it supports reverse lookup and traversal to facilitate operations. However, it brings some additional memory overhead and many internal implementations of Redis, this data structure is also used, including the sending Buffer Queue.
- Set
Common commands:
Sadd, spop, smembers, and sunion.
Application scenarios:
The functions provided by Redis set are similar to those provided by list. The special feature is that set can automatically record duplicates. When you need to store a list of data, if you do not want duplicate data, set is a good choice, and set provides an important interface to determine whether a member is in a set. This is also not provided by list.
Implementation Method:
The internal implementation of set is a HashMap whose value is always null. Actually, it is to calculate the hash method to quickly remove duplicates, this is also why set can determine whether a member is in the set.
- Sorted set
Common commands:
Zadd, zrange, zrem, zcard, etc.
Use Cases:
The usage scenario of Redis sorted set is similar to set. The difference is that set is not automatically ordered, while sorted set can sort members by providing an additional priority (score) parameter, it is insert-ordered, that is, automatic sorting. When you need an ordered and non-repeated list of sets, you can choose sorted set data structure. For example, twitter's public timeline can be stored as score by posting time, in this way, the query is automatically sorted by time.
Implementation Method:
In Redis sorted set, HashMap and SkipList are used internally to ensure data storage and order. In HashMap, Members are mapped to scores, the hop table stores all the members, and the sorting is based on the score saved in HashMap. using the structure of the hop table, you can get a high search efficiency and the implementation is relatively simple.
Before using Redis in Java, make sure that you have installed the redis service and the Java redis driver, and your machine can use Java normally. For Java installation configuration, refer to our Java Development Environment configuration. Next let's install the Java redis DRIVER:
- First, you need to download the driver package,Download jedis. jarTo download the latest driver package.
- Include the driver package in your classpath.Ii. Use of java Jedis connection pool
Required jar: jedis-2.1.0.jar and commons-pool-1.5.4.jar
The Jedis procedure is as follows:
1-> the Jedis instance needs to be obtained from the JedisPool;
2-> when the Jedis instance is used up, it must be returned to the JedisPool;
3-> If a Jedis error occurs during use, return it to the JedisPool;
Package redisJava; import redis. clients. jedis. jedis; import redis. clients. jedis. jedisPool; import redis. clients. jedis. jedisPoolConfig; public class RedisJava {private static JedisPool jedisPool; // Jedis connection pool/*** @ function to build a redis connection pool * @ author pifeng * @ return * @ date July 15, March 29, 2016 */public static JedisPool getPool () {if (jedisPool = null) {JedisPoolConfig config = new JedisPoolConfig (); // controls how many jedis instances can be allocated to a pool. Ol. getResource () is obtained. // if the value is-1, it indicates no restriction. If maxActive jedis instances have been allocated to the pool, the pool status is exhausted (depletion ). Config. setMaxActive (500); // controls the maximum number of idle jedis instances in a pool. Config. setMaxIdle (5); // indicates the maximum waiting time when borrow (introduced) is a jedis instance. If the waiting time is exceeded, JedisConnectionException is thrown directly; config. setMaxWait (1000*100); // whether to perform the validate operation in advance when a jedis instance is in borrow; if it is true, the jedis instance is available; config. setTestOnBorrow (true); jedisPool = new JedisPool (config, "192.168.10.241", 6379);} return jedisPool ;} /*** @ function return to connection pool * @ author pifeng * @ param pool * @ param redis * @ date July 22, March 29, 2016 */public static void returnRe Source (JedisPool, Jedis redis) {if (redis! = Null) {pool. returnResource (redis );}} /*** @ function to obtain data * @ author pifeng * @ param key * @ return * @ date February */public static String getString (String key) {String value = null; jedisPool pool = null; Jedis jedis = null; try {pool = getPool (); jedis = pool. getResource (); value = jedis. get (key) ;}catch (Exception e) {// release the redis Object pool. returnBrokenResource (jedis); e. printStackTrace ();} finally {// return to the connection pool returnResource (pool, jedis);} return value ;} /*** @ function set data * @ author pifeng * @ param key * @ param value * @ return * @ date January 1, March 29, 2016 */public static boolean setString (String key, string value) {JedisPool = null; Jedis jedis = null; try {pool = getPool (); jedis = pool. getResource (); value = jedis. set (key, value);} catch (Exception e) {// release the redis Object pool. returnBrokenResource (jedis); e. printStackTrace (); return false;} finally {// return to the connection pool returnResource (pool, jedis);} return true ;} /*** @ function test * @ author pifeng * @ param args * @ date February */public static void main (String [] args) {setString ("sex ", "male"); setString ("name", "pifeng"); setString ("age", "24"); System. out. println (getString ("sex"); System. out. println (getString ("name"); System. out. println (getString ("age "));}}3. Connect to the redis Service
Import redis. clients. jedis. jedis; public class RedisJava {public static void main (String [] args) {// connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System. out. println ("Connection to server sucessfully"); // check whether the service is running System. out. println ("Server is running:" + jedis. ping ());}}
Compile the above Java program to ensure that the path of the driver package is correct.
$javac RedisJava.java$java RedisJavaConnection to server sucessfullyServer is running: PONGRedis Java String Example
4. Redis Java String instance
Import redis. clients. jedis. jedis; public class RedisStringJava {public static void main (String [] args) {// connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System. out. println ("Connection to server sucessfully"); // sets the redis string data jedis. set ("w3ckey", "Redis tutorial"); // obtain the stored data and output the System. out. println ("Stored string in redis:" + jedis. get ("w3ckey "));}}
Compile the above program.
$javac RedisStringJava.java$java RedisStringJavaConnection to server sucessfullyStored string in redis:: Redis tutorial
V. Redis Java List instance
Import redis. clients. jedis. jedis; public class RedisListJava {public static void main (String [] args) {// connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System. out. println ("Connection to server sucessfully"); // store data to jedis in the list. lpush ("tutorial-list", "Redis"); jedis. lpush ("tutorial-list", "Mongodb"); jedis. lpush ("tutorial-list", "Mysql"); // obtain the stored data and output the List
List = jedis. lrange ("tutorial-list", 0, 5); for (int I = 0; I
Compile the above program.
$javac RedisListJava.java$java RedisListJavaConnection to server sucessfullyStored string in redis:: RedisStored string in redis:: MongodbStored string in redis:: Mysql
6. Redis Java Keys instance
Import redis. clients. jedis. jedis; public class RedisKeyJava {public static void main (String [] args) {// connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System. out. println ("Connection to server sucessfully"); // obtain the data and output the List
List = jedis. keys ("*"); for (int I = 0; I
Compile the above program.
$javac RedisKeyJava.java$java RedisKeyJavaConnection to server sucessfullyList of stored keys:: tutorial-nameList of stored keys:: tutorial-list