In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "SpringBoot how to use RedisTemplate to operate Redis data type", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "SpringBoot how to use RedisTemplate to operate Redis data type" bar!
Spring encapsulates RedisTemplate to manipulate Redis, which supports all Redis native API. The operation methods for five kinds of data structures are defined in RedisTemplate.
OpsForValue (): operation string.
OpsForList (): list of operations.
OpsForHash (): manipulate the hash.
OpsForSet (): operations collection.
OpsForZSet (): an ordered collection of operations.
The following examples are used to understand and apply these methods. It should be noted here that the data should be emptied after running the above method, otherwise running multiple times will lead to repeated data operations.
(1) use Maven to add dependent files
In the pom.xml configuration information file, add Redis dependencies:
My SpringBoot version:
Org.springframework.boot spring-boot-starter-parent 2.3.4.RELEASE
Add Redis dependencies:
Org.springframework.boot spring-boot-starter-data-redis 2.3.3.RELEASE
(2) configuration of Redis
Configure Redis information in the application.yml configuration file:
# Spring configuration spring: # cache manager cache: type: redis # Redis configuration redis: database: 0 # Redis database index (default is 0) host: 127.0.0.1 # Redis server address port: 6379 # Redis server connection port password: # Redis server connection password (default is empty) jedis: pool: max-active: 8 # connection Maximum number of connections in the pool (using negative values for unlimited) max-wait:-1s # maximum blocking wait time for the connection pool (using negative values for unlimited) max-idle: maximum idle connections in the 8 # connection pool min-idle: 0 # minimum idle connections in the connection pool lettuce: shutdown-timeout: 100ms # shutdown timeout Default value 100ms
(3) Redis configuration class (config layer)
Create the com.pjb.config package, create the RedisConfig class (Redis configuration class), and inherit the CachingConfigurerSupport class.
Package com.pjb.config; import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate In the import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.lang.reflect.Method; / * * Redis configuration class * @ author pan_junbiao * * / @ Configurationpublic class RedisConfig extends CachingConfigurerSupport {/ * cache object collection, the cache is saved in the form of key-value. * when the cached key is not specified, SpringBoot uses keyGenerator to generate Key. * / @ Bean public KeyGenerator keyGenerator () {return new KeyGenerator () {@ Override public Object generate (Object target, Method method, Object...) Params) {StringBuilder sb = new StringBuilder (); / / Class name + method name sb.append (target.getClass (). GetName ()); sb.append (method.getName ()); for (Object obj: params) {sb.append (obj.toString ()) } return sb.toString ();}};} / * Cache Manager * / @ SuppressWarnings ("rawtypes") @ Bean public CacheManager cacheManager (RedisConnectionFactory connectionFactory) {RedisCacheManager cacheManager = RedisCacheManager.create (connectionFactory); / / set cache expiration time return cacheManager Instantiate RedisTemplate object * / @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate (factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om) Template.setValueSerializer (jackson2JsonRedisSerializer); template.afterPropertiesSet (); return template;}} 1, string (String)
String (String) is the most basic data type of Redis. A "Key" of String corresponds to a "Value", that is, a Key-Value key-value pair. String is binary secure and can store any data (such as pictures or serialized objects). The maximum value can store the data of 512MB. It is generally used for caching of some complex counting functions. RedisTemplate provides the following methods for manipulating String.
1.1 void set (K key, V value); V get (Object key)
For specific usage, see the following code:
/ * Redis operation string (String) * @ author pan_junbiao * * / @ SpringBootTestpublic class StringTest {@ Autowired private RedisTemplate redisTemplate; @ Testpublic void string1 () {redisTemplate.opsForValue () .set ("userName", "pan_junbiao 's blog"); redisTemplate.opsForValue () .set ("blogUrl", "https://blog.csdn.net/pan_junbiao");") RedisTemplate.opsForValue () .set ("blogRemark", "Hello, welcome to pan_junbiao 's blog"); System.out.println ("user name:" + redisTemplate.opsForValue () .get ("userName")); System.out.println ("blog address:" + redisTemplate.opsForValue () .get ("blogUrl")); System.out.println ("blog message:" + redisTemplate.opsForValue () .get ("blogRemark")) }}
Execution result:
1.2 void set (K key, V value, long timeout, TimeUnit unit)
The following code sets 3s to fail. The query has a result within 3 seconds, and the query returns null after 3 seconds. For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void string2 () {/ / set 3s invalidation, query results within 3s, and return null redisTemplate.opsForValue () .set ("blogRemark", "Hello, Welcome to pan_junbiao 's blog", 3, TimeUnit.SECONDS); try {Object S1 = redisTemplate.opsForValue () .get ("blogRemark"); System.out.println ("blog info:" + S1) Thread.currentThread () .sleep (2000); Object S2 = redisTemplate.opsForValue () .get ("blogRemark"); System.out.println ("blog info:" + S2); Thread.currentThread () .sleep (5000); Object S3 = redisTemplate.opsForValue () .get ("blogRemark"); System.out.println ("blog info:" + S3) } catch (InterruptedException ie) {ie.printStackTrace ();}}
Execution result:
1.3V getAndSet (K key, V value)
Sets the string for the key and returns its old value. For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void string3 () {/ / sets the string of the key and returns its old value redisTemplate.opsForValue (). Set ("blogRemark", "pan_junbiao 's blog"); Object oldVaule = redisTemplate.opsForValue (). GetAndSet ("blogRemark", "Hello, welcome to pan_junbiao 's blog"); Object newVaule = redisTemplate.opsForValue (). Get ("blogRemark"); System.out.println ("Old value:" + oldVaule) System.out.println ("New value:" + newVaule);}
Execution result:
1.4 Integer append (K key, V value)
If key already exists and is a string, the command appends the value to the end of the string. If key does not exist, it will be created and set to an empty string, so append is similar to set in this special case. For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void string4 () {/ / set the serialization rules of value, otherwise you will get an error redisTemplate.setValueSerializer (new StringRedisSerializer ()); redisTemplate.opsForValue () .append ("blogRemark", "Hello, welcome to visit"); System.out.println (redisTemplate.opsForValue (). Get ("blogRemark")); redisTemplate.opsForValue () .append ("blogRemark", "pan_junbiao 's blog") System.out.println (redisTemplate.opsForValue () .get ("blogRemark");}
Execution result:
Note: be sure to deserialize the configuration here, otherwise an error will be reported.
1.5 Long size (K key)
Returns the length of the value corresponding to key, as shown in the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void string5 () {redisTemplate.opsForValue () .set ("userName", "pan_junbiao 's blog"); System.out.println ("value:" + redisTemplate.opsForValue () .get ("userName")); System.out.println ("length of value:" + redisTemplate.opsForValue () .size ("userName"));}
Execution result:
2. List (List)
The Redis list is a simple list of strings sorted in the order in which they are inserted. You can add an element to the head (left) or tail (right) of the list.
Using list data results, you can do simple message queuing functions. You can also use the Irange command to do Reids-based paging with excellent performance.
2.1 Long leftPushAll (K key, V... Values); Long rightPushAll (K key, V... Values)
The leftPushAll method: inserts an array into the list.
RightPushAll method: means to add elements in batches to the rightmost part of the list. For specific usage, see the following code:
/ * * Redis Action list (List) * @ author pan_junbiao * * / @ SpringBootTestpublic class ListTest {@ Autowired private RedisTemplate redisTemplate; @ Testpublic void list1 () {String [] user1 = new String [] {"1", "pan_junbiao 's blog", "Hello, welcome to pan_junbiao 's blog"} String [] user2 = new String [] {"2", "pan_junbiao blog", "https://blog.csdn.net/pan_junbiao"}; String [] user3 = new String [] {" 3 "," pan_junbiao blog "," Hello, welcome to pan_junbiao blog "}; redisTemplate.opsForList (). RightPushAll (" user1 ", user1); redisTemplate.opsForList (). RightPushAll (" user2 ", user2) RedisTemplate.opsForList (). RightPushAll ("user3", user3); System.out.println (redisTemplate.opsForList (). Range ("user1", 0mam Raqui1)); System.out.println (redisTemplate.opsForList (). Range ("user2", 0mam Murray 1)); System.out.println (redisTemplate.opsForList (). Range ("user3", 0mam 1));}}
Execution result:
2.2 Long leftPush (K key, V value); Long rightPush (K key, V value)
LeftPush method: inserts all specified values at the head of the list of keys. If the key does not exist, it is created as an empty list (inserted from the left) before the push operation is performed.
RightPush method: inserts all specified values at the end of the list of keys. If the key does not exist, it is created as an empty list (insert from the right) before the push operation is performed. For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void list2 () {redisTemplate.opsForList () .rightPush ("userInfo", 1); redisTemplate.opsForList () .rightPush ("userInfo", "pan_junbiao 's blog"); redisTemplate.opsForList () .rightPush ("userInfo", "https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForList () .rightPush (" userInfo "," Hello, welcome to pan_junbiao 's blog ") System.out.println ("user ID:" + redisTemplate.opsForList (). Index ("userInfo", 0)); System.out.println ("user name:" + redisTemplate.opsForList (). Index ("userInfo", 1)); System.out.println ("blog address:" + redisTemplate.opsForList (). Index ("userInfo", 2)); System.out.println ("blog message:" + redisTemplate.opsForList (). Index ("userInfo", 3));}
Execution result:
2.3 Long size (K key)
Returns the length of the list stored in the key. If the key does not exist, it is interpreted as an empty list and 0 is returned. If the value that exists in key is not a list, an error is returned. For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void list3 () {String [] user = new String [] {"1", "pan_junbiao blog", "Hello, welcome to pan_junbiao blog"}; redisTemplate.opsForList () .leftPushAll ("user", user); System.out.println ("length of list:" + redisTemplate.opsForList () .size ("user"));}
Execution result:
2.4 void set (K key, long index, V value)
Set the value at the location of the index in the list. For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void list4 () {String [] user = new String [] {"1", "pan_junbiao 's blog", "https://blog.csdn.net/pan_junbiao"}; redisTemplate.opsForList (). RightPushAll (" user ", user); System.out.println (redisTemplate.opsForList (). Range (" user ", 0mairelle 1)); redisTemplate.opsForList () .set (" user ", 2," Hello, welcome to pan_junbiao 's blog ") System.out.println (redisTemplate.opsForList (). Range ("user", 0mermer1));}
Execution result:
2.5V index (K key, long index)
Gets the value in the list based on the subscript (the subscript starts at 0). For specific usage, see the following code:
@ Autowiredprivate RedisTemplate redisTemplate; @ Testpublic void list2 () {redisTemplate.opsForList () .rightPush ("userInfo", 1); redisTemplate.opsForList () .rightPush ("userInfo", "pan_junbiao 's blog"); redisTemplate.opsForList () .rightPush ("userInfo", "https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForList () .rightPush (" userInfo "," Hello, welcome to pan_junbiao 's blog ") System.out.println ("user ID:" + redisTemplate.opsForList (). Index ("userInfo", 0)); System.out.println ("user name:" + redisTemplate.opsForList (). Index ("userInfo", 1)); System.out.println ("blog address:" + redisTemplate.opsForList (). Index ("userInfo", 2)); System.out.println ("blog message:" + redisTemplate.opsForList (). Index ("userInfo", 3));}
Execution result:
2.6 Long remove (K key, long count, Object value)
Removes the first count event of an element with a given "count" value from the list stored in the key. Parameter count is defined as follows:
Count=0: delete all elements equal to value.
Count > 0: deletes an element equal to the value moved from beginning to end.
Count
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.