Preface
This article uses Spring Data Redis to operate the local Redis database, which is only for records in learning.
Redis
Introduction
- Redis is an open source free, high-performance key-value database.
- Redis supports persistence of data, which can keep data in memory on disk and can be loaded again for use during restart.
- All operations of Redis are atomic, and Redis also supports atomic execution after the whole merge of several operations.
- The speed of Redis can read is 110,000 times/s and the speed of write is 81,000 times/s.
- Because Redis data is stored in memory, it is very simple to operate in memory compared to databases such as MySQL, and can do many things with strong internal complexity. Moreover, the data in Redis is compact and generated in an append manner, because Redis data does not require random access.
Redis index
In redis, the index starts from 0 and the command contains range, the starting index is included.
If there is a String<name , code_laoq>
, the string substring obtained using getrange name 1 3 is ode.
If the index is negative, it means that it is a certain element that is the countdown. If there is List<weekday, [Monday,Tuesday,Wednesday,Thursday,Friday]>, uselindex weekday -2
What you get is the second last element of List, namely Thursday.
Data Type
Redis supports five data types: string (string), hash (hash), list (list), set (set) and zset (sorted set: ordered set).
String (String)
- string is the most basic type of redis. You can understand it as a type exactly the same as Memcached, with a key corresponding to a value.
- The string type is binary safe. Meaning that redis's string can contain any data. For example, jpg image or serialized object.
- The string type is the most basic data type of Redis, and a key can store up to 512MB.
Hash (hash)
- Redis hash is a key-value pair collection, a mapping table of fields and values of string type, suitable for storing Object objects.
List (list)
- A Redis list is a simple list of strings sorted in the order of insertion. An element can be added to the head (left) or the tail (right) of the list.
Set (set)
- Redis Set is an unordered set of string type, implemented through a hash table, so the complexity of addition, deletion, and search are all O(1).
zset(sorted set: ordered set)
- Redis zset is also a collection of string-type elements, and duplicate members are not allowed.
- The difference is that each element will associate a score of double type.
- redis uses score to sort members in a collection from small to large.
The members of zset are unique, but score can be repeated.
Redis command
Redis Data Management
- Deletes the data of the specified key.
DEL key_name
- Check whether the data of the specified key exists. If the key exists, return 1, otherwise return 0.
EXISTS key_name
- Check the type of the specified key, the return value is: none (key does not exist), string, list, set, zset, or hash.
TYPE key_name
- Fuzzy query, similar to mysql.
keys *lock*
From query data containing lock in key
KEYS pattern
- Modify the key value of the specified key (its value remains unchanged), and overwrite it if new_key_name exists
RENAME old_key_name new_key_name
- When the new_key_name data does not exist, modify the key_name of the specified key
RENAMENX old_key_name new_key_name
- Add expiration time to the specified key
EXPIRE key_name expiration --Set the specifiedkeyexist[expiration]Expired in seconds EXPIREAT key_name timestamp --The parameters areUNIXTimestamp(from1970Year1moon1Day begins,The number of seconds elapsed to the current time) PEXPIRE key_name milliseconds --Expiration time is calculated in milliseconds PEXPIREAT key milliseconds-timestamp --UNIXTimestamp以毫秒计算
- Remove the expiration time of the specified key
PERSIST key_name
- View the expiration time of the specified key
TTL key_name --Returns the remaining expiration time(In seconds) PTTL key_name --Returns the remaining expiration time(In milliseconds)
- Move the specified key to the specified database
MOVE key_name db_num
Redis String
- Modify the value of the key(Ignore the type), if it does not exist, add a new data with a value value.
SET key_name value
- Set the value of the given key to value and return the original value. If the key does not exist, it will be added, but will return null.
GETSET key_name value
- Set the value and its expiration time for the specified key toexpiration(Units in seconds). If the key does not exist, it will be added.
SETEX key_name out_time value
- Similar to SETEX, but it sets the survival time of the specified key in milliseconds.
PSETEX key_name expiration value
- Add a new data, and if the key already exists, it will not be executed.
SETNX key_name value
- Add multiple pieces of data, and if it already exists, modify the values of these keys. What if some keys exist and some keys do not exist? Then add something that does not exist, modify it to exist.
MSET key_name1 value1 key_name2 value2 ... key_nameN valueN
- Add multiple pieces of data, if any key already exists, no insertion operation is performed [It will affect the fish in the pond, and no one will be inserted】。
MSETNX key_name1 value1 key_name2 value2 ... key_nameN valueN
- Append value to the end of the specified key original value. If it does not exist, it will be added.
APPEND key_name value
- Get the value of the specified key
GET key_name
- Get the values of multiple keys
mget key_name1 key_name2 ... key_nameN
- Get the substring of the specified key
GETRANGE key_name start end
- Gets the length of the string value stored by the specified key.
STRLEN key_name
Redis hash (Hash)
Redis List (List) operation command
- Insert data to the left of List.Even if the key does not exist, it can be inserted.
LPUSH key_name value_1 value_2 ... value_n --Each data is separated by spaces
- Insert a piece of data to the left of the existing List.Only one data can be inserted at a time; if List does not exist, it cannot be inserted
LPUSHX key_name value
- Insert data to the right of List. value_2 is on the right side of value_1,Even if the key does not exist, it can be inserted.
RPUSH key_name value_1 value_2 ... value_n
- Insert a data to the right of the existing List
RPUSHX key_name value
- Insert a data before/after a certain element of List.If List or specified element does not exist, data cannot be inserted
LINSERT key_name BEFORE existing_value new_value LINSERT key_name AFTER existing_value new_value
- Get List length
LLEN key_name
- Get elements in List by index. This index value only requires an integer, and if the index goes beyond the bounds, a null will be returned.
LINDEX key_name index
- Gets elements within the range specified by List. What is obtained is the element in the closed interval [start, stop].
LRANGE key_name start stop
- Batch remove List elements. According to the COUNT value, remove the element in the List that is equal to VALUE.
- count > 0 : Starting from the head of the table, searching to the end of the table, remove elements equal to VALUE, with the number COUNT.
- count < 0 : Starting from the end of the table, searching the table header, remove elements equal to VALUE, with the absolute value of COUNT.
- count = 0: Removes all values in the table that are equal to VALUE.
LREM key_name COUNT value
- Remove and get the last element of List
RPOP key_name
Redis collection (Set)
- Redis Ordered Set (sorted set)
Introducing Redis
Import Maven coordinates
When using MySQL in Java, it uses the JDBC interface, and there are also interfaces for operating Redis. Common ones include Jedis, Lettuce and Spring Data Redis. Spring Data Redis encapsulates the first two interfaces.
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
Configure Redis database information
blog: #Fill in the abbreviation of the project here, do not copy it redis: host: localhost #You can also fill in the remote IP port: 6379 #Port Number password: #Password, redis has no password by default, it needs to be modified in the configuration file database: 8 #Database number to connect to
Write the configuration class RedisConfiguration
In the configuration class
Redis database configuration information
package ; import .slf4j.Slf4j; import ; import ; import ; import ; import ; /** @author code_laoq @version 1.0 @date 2024/11/3 19:48 @description Redis database configuration information */ @Configuration @Slf4j public class RedisConfiguration { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) { (“createredistemplate”); RedisTemplate redisTemplate=new RedisTemplate(); (factory); (new StringRedisSerializer()); return redisTemplate; } }
Operate Redis database
Recalling what object to use for MySQL before, it is the JDBCemplate object. Similarly, in SpringBoot, RedisTemplate objects are generally used to operate the Redis database.
;
RedisTemplate provides various redis operations, exception handling and serialization.
! ! ! Redis does not have unified SQL statements similar to MySQL and other relational databases, which means that different statements must be used for different types of data structures. For example, inserting a String type data and a List type data requires different statements.
--StringInsert data SET name laoq --ListInsert data RPUSH KEY_NAME VALUE1
Therefore, the operation statement of each Redis data structure must be learned (similarly the same), and I will start with the RedisTemplate object to explain it below.
RedisTemplate object
RedisTemplate provides various redis operations, exception handling and serialization. The five common OpsFors in RedisTemplate are:opsForValue()、opsForList()、opsForHash()、opsForSet()、OpsForZSet()。Obviously, they are methods of operating String, List, Hash, Set and Zset in Redis.
opsForValue()
Let's first look at the prototype of opsForValue().
public ValueOperations<K, V> opsForValue() { return ; }
This method returns an interface of type ValueOperations, which defines 17 methods for operating redis strings. Calling the opsForValue() method of RedisTemplate will return the property of the DefaultValueOperations implementation class object of the ValueOperations interface.
Let's look at the ValueOperations method one by one.
set()
void set(K key, V value); void set(K key, V value, long timeout, TimeUnit unit);
The set(K key, V value) method corresponds to the SET key value statement of Redis, which is used to insert a data. The key and value are the key values of the data respectively.
The overloaded set(K key, V value, long timeout, TimeUnit unit) method corresponds to the SETEX key seconds value statement of Redis, inserts a data with an expiration date, timeout is the expiration time, and unit is the time unit.
Here is an example
@Test public void testRedisString(){ ().set("name","code_laoq"); ().set("CAPTCHA","p2um",5, );//Expiration in 5 minutes}
setIfAbsent()
Boolean setIfAbsent(K key, V value); Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit);
The setIfAbsent() method is used for Redis's SETNX key value. If the data corresponding to the key does not exist, it will be inserted, otherwise it will not be inserted. Parameters are the same as above. I will not repeat them again
setIfPresent()
Boolean setIfPresent(K key, V value); Boolean setIfPresent(K key, V value, long timeout, TimeUnit unit);
The setIfAbsent() method for Redis's SET key value [EX seconds/PX millionseconds] XX, insert and return True if the data corresponding to the key exists, otherwise it will return False if it does not insert. It is equivalent to an update operation.
Examples are as follows:
@Test public void testRedisString(){ ().setIfPresent("CAPTCHA1","laoq",5, ); }
opsForList()
Let's look at the prototype of the method first
public ListOperations<K, V> opsForList() { return ; }
Similar to the above, this method returns an interface of type ListOperations, which defines 17 methods for operating redis strings. Calling the opsForList() method of RedisTemplate will return the property of the DefaultListOperations implementation class object of the ListOperations interface. Let's look at the ListOperations method one by one.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.