Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Template to operate Redis in StringRedis

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people have no idea about how to use Template to operate Redis in StringRedis. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

How to use StringRedisTemplate to operate Redis an introduction to Redis in detail

Redis is an open source (BSD licensed), in-memory data structure storage system that can be used as database, cache, and messaging middleware. New stream data types are supported for transaction version 5. 0.

Spring boot single data source configuration

Springboot's redis single data source configuration is very simple.

(1) configure appliation.properties file

Database number of spring.redis.host=x.x.x.xspring.redis.port=6379#redis spring.redis.database=4spring.redis.timeout = 30000msspring.redis.jedis.pool.max-active=200spring.redis.jedis.pool.max-idle=0spring.redis.lettuce.pool.max-idle=5spring.redis.jedis.pool.max-wait=20000ms

(2) basic operation of StringRedisTemplate

StringRedisTemplate automatically closes redis connection / / injects object @ Autowiredprivate StringRedisTemplate stringRedisTemplate;# to get ValueOperations operation String data ValueOperations valueOperations = stringRedisTemplate.opsForValue (); valueOperations.set ("strRedis", "StringRedisTemplate"); valueOperations.get ("strRedis"); # sets expiration time set ("timeStep", new Date (). GetTime () + ", 2, TimeUnit.MINUTES); # get SetOperations operation Set data SetOperations set = stringRedisTemplate.opsForSet (); set.add (" set1 "," 22 ") Set.add ("set1", "33"); set.add ("set1", "44"); Set resultSet = stringRedisTemplate.opsForSet (). Members ("set1"); stringRedisTemplate.opsForSet (). Add ("set2", "1", "2", "3"); / / deposit the set collection Set resultSet1 = stringRedisTemplate.opsForSet (). Members ("set2") in the specified key; log.info ("resultSet:" + resultSet); log.info ("resultSet1:" + resultSet1) # obtain List data for ListOperations operations. List can be used to implement queues. / / add data to the left side of existing data corresponding to key Long redisList = stringRedisTemplate.opsForList (). LeftPush ("redisList", "3"); stringRedisTemplate.opsForList (). LeftPush ("redisList", "4"); / / add data to the right side of existing data corresponding to key Long size = stringRedisTemplate.opsForList (). Size ("redisList"); / / traverse from left to right String leftPop = stringRedisTemplate.opsForList (). LeftPop ("redisList") / / iterate through String rightPop = stringRedisTemplate.opsForList (). RightPop ("redisList") from right to left; / / query all elements List range = stringRedisTemplate.opsForList (). Range ("redisList", 0,-1); / / query the first three elements List range1 = stringRedisTemplate.opsForList (). Range ("redisList", 0,3) / / remove element A from list (1: from left to right-1: from right to left 0: delete all) Long remove = stringRedisTemplate.opsForList () .remove ("key", 1, "A"); log.info ("redisList----" + redisList); log.info ("size----" + size); log.info ("leftPop----" + leftPop); log.info ("rightPop----" + rightPop); log.info ("range----" + range) Log.info ("range1----" + range1); log.info ("remove----" + remove); / / determine whether hashBoolean aBoolean = stringRedisTemplate.opsForHash (). HasKey ("hash", "hash2") exists in the map corresponding to key; / / add (key1,value1) stringRedisTemplate.opsForHash (). Put ("hash", "hash2", "value1") to the map corresponding to key. / / get the value of hash2 in the map corresponding to key Object o = stringRedisTemplate.opsForHash (). Get ("hash", "hash2"); / / delete multiple sub-hash (variable parameter) Long delete = stringRedisTemplate.opsForHash (). Delete ("hash", "key1", "key2", "key3") in the map corresponding to key; / / obtain mapMap hash = stringRedisTemplate.opsForHash () .entries ("hash") corresponding to hash. / / get all subhash sets in map corresponding to hash Set hash2 = stringRedisTemplate.opsForHash (). Keys ("hash"); / / get all value collections in map corresponding to hash List hash3 = stringRedisTemplate.opsForHash (). Values ("hash"); # delete key Boolean key = stringRedisTemplate.delete ("key"); # numeric plus xLong count = stringRedisTemplate.boundValueOps ("count"). Increment (1) / / val + 1 # get the expiration time. If not,-1Long time = stringRedisTemplate.getExpire ("count") Spring boot multi-data source configuration, configure a library 1, a library 4

Add dependency

Org.apache.commons commons-pool2 org.springframework.boot spring-boot-starter-data-redis

Modify application.properties configuration file

# Library 1 spring.redis.redis-onedb.database=0spring.redis.redis-onedb.hostName=192.168.90.42spring.redis.redis-onedb.port=9110spring.redis.redis-onedb.timeout=5000#4 Library spring.redis.redis-fourdb.database=4spring.redis.redis-fourdb.hostName=192.168.90.42spring.redis.redis-fourdb.port=9110spring.redis.redis-fourdb.timeout=5000

Create a RedisConfig.java file

@ Configurationpublic class RedisConfig {[@ Bean] (https://my.oschina.net/bean)@ConfigurationProperties(prefix = "spring.redis.lettuce.pool") @ Scope (value = "prototype") public GenericObjectPoolConfig redisPool () {return new GenericObjectPoolConfig ();} @ Bean@ConfigurationProperties (prefix = "spring.redis.redis-fourdb") public RedisStandaloneConfiguration redisConfigA () {return new RedisStandaloneConfiguration ();} @ Bean@ConfigurationProperties (prefix = "spring.redis.redis-onedb") public RedisStandaloneConfiguration redisConfigB () {return new RedisStandaloneConfiguration () } @ Primary@Beanpublic LettuceConnectionFactory factoryA (GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigA) {LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder () .poolConfig (config) .commandTimeout (Duration.ofMillis (config.getMaxWaitMillis () .build (); return new LettuceConnectionFactory (redisConfigA, clientConfiguration);} @ Beanpublic LettuceConnectionFactory factoryB (GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigB) {LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder () .poolConfig (config) .commandTimeout (Duration.ofMillis (config.getMaxWaitMillis () .build (); return new LettuceConnectionFactory (redisConfigB, clientConfiguration) } @ Bean (name = "fourRedis") public StringRedisTemplate redisBusTemplate (@ Qualifier ("factoryA") LettuceConnectionFactory factoryA) {StringRedisTemplate template = getRedisTemplate (); template.setConnectionFactory (factoryA); return template;} @ Bean (name = "oneRedis") public StringRedisTemplate redisLoginTemplate (@ Qualifier ("factoryB") LettuceConnectionFactory factoryB) {StringRedisTemplate template = getRedisTemplate (); template.setConnectionFactory (factoryB); return template;} private StringRedisTemplate getRedisTemplate () {StringRedisTemplate template = new StringRedisTemplate (); template.setValueSerializer (new GenericFastJsonRedisSerializer ()) Template.setValueSerializer (new StringRedisSerializer ()); return template;}

In classes that need to be used, injection can be used

@ Resource (name = "oneRedis") private StringRedisTemplate oneRedis;@Resource (name = "fourRedis") private StringRedisTemplate fourRedis;StringRedisTemplate implements transaction stringRedisTemplate.setEnableTransactionSupport (true); try {stringRedisTemplate.multi (); / / Open transaction stringRedisTemplate.opsForValue (). Increment ("count", 1); stringRedisTemplate.opsForValue (). Increment ("count1", 2); / / commit stringRedisTemplate.exec () } catch (Exception e) {log.error (e.getMessage (), e); / / enable rollback stringRedisTemplate.discard ();}

* * Note: * * after StringRedisTemplate starts the transaction, the connection will not be released. If we use Spring transaction management, this problem does not exist.

StringRedisTemplate implements optimistic locks redisTemplate.watch ("key"); / / 1redisTemplate.multi (); redisTemplate.boundValueOps ("key"). Set ("" + id "); List list= redisTemplate.exec (); System.out.println (list); if (list! = null) {/ / operation success System.out.println (id+" operation success ");} else {/ / operation failure System.out.println (id+" operation failure ") } StringRedisTemplate implements pipe pipeline StringRedisTemplate implements distributed locks String lockKey = "key"; String lockValue = lockKey+System.currentTimeMillis (); / / value needs to remember to unlock while (true) {Boolean ifPresent = stringRedisTemplate.opsForValue (). SetIfAbsent ("redis-lock:" + lockKey, lockValue, 3, TimeUnit.SECONDS); if (ifPresent) {log.info ("get redis-lock success"); break;}} / / unlock String lockKey = "key"; String lockValue = lockKey + System.currentTimeMillis (); boolean result = false; / / value need to remember to unlock stringRedisTemplate.watch ("redis-lock:" + lockKey); String value = stringRedisTemplate.opsForValue (). Get ("redis-lock:" + lockKey) If (null = = value) {result = true;} else if (value.equals (lockValue)) {stringRedisTemplate.delete ("redis-lock:" + lockKey); result = true;} stringRedisTemplate.unwatch () Redis cache breakdown, penetration and avalanche cache breakdown means that a key is very hot, constantly carrying large concurrency and focusing on accessing this point. When the key expires, persistent large concurrency will break through the cache and directly request the database, just like cutting a hole in a barrier to query data that must not exist in a database. The normal process of using caching is that data query is first cached. If key does not exist or key has expired, then query the database, and put the queried objects into the cache. If the database query object is empty, it is not cached. The solution is to set the cache time to be shorter even if the checked object is empty. Cache avalanche means that the cache set expires in a certain period of time. After reading the above, have you mastered how to use Template to operate Redis in StringRedis? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report