You can obtain the key value by using the keys command in Redis. The specific command format is keys pattern
There are three wildcards in Redis that allow fuzzy query, respectively: *,? And []
Among them:
* : wildcard any multiple characters
? : Wildcard a single character
[] : indicates a character in the wildcard brackets
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
In a real project, it is possible to use Spring’s RedisTemplate integrated with Redis to do this, so fuzzy queries may not work well when injecting templates. The keys method exists in a subclass of StringRedisTemplate (superclass -RedisTemplate)
Be careful when configuring Spring!!
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Specific ideas in actual operation:
1. ZSet the conditions to be queried as keys
Keys (pattern) string redistemplate. keys(pattern)
PublicSet keys (String pattern) {returnstringRedisTemplate. Keys ("*"+ pattern + "*");
// return stringRedisTemplate.keys("?"+ the pattern); //return stringRedisTemplate.keys("[" + pattern + "]");
}Copy the code
Ps: Fuzzy lookup applies to String data structures. Other structures supported by Redis (List, set, etc.) are not verified.
Practice code:
/ * * * redis buffer action class * / @ ServicepublicclassRedisCacheServiceimplementsInitializingBean {privateValueOperations valueOperations; @AutowiredprivateStringRedisTemplate redisTemplate; @SuppressWarnings("unchecked")@OverridepublicvoidafterPropertiesSet()throwsException{RedisSerializer redisSerializer =newStringRedisSerializer(); valueOperations = redisTemplate.opsForValue(); } /** * get the resource information from the cache *@paramkey*@return
*/publicListgetCacheResource(String key){
Set<String> keys = redisTemplate.keys(key);if(CollectionUtils.isEmpty(keys))
{returnnewArrayList<>();
}
List resourceCacheBOList =newArrayList<>();for(String accurateKey : keys) {
String cacheValue = valueOperations.get(accurateKey);
List<ResourceCacheBO> sub = JSONArray.parseArray(cacheValue,
ResourceCacheBO.class);
resourceCacheBOList.addAll(sub);
}returnresourceCacheBOList; }Copy the code
[Key exists, redisTemplate cannot find]
Problem: There is key: “A_091_JPFX”, but with fuzzy key: “A_*_JPFX” match, but cannot match; Some information says it is a coding problem, which can be solved as follows:
When redistemplate. keys is used to search keys, it is found that the corresponding key clearly exists, but fuzzy query cannot find it. There are two reasons:
1. Make sure your query string is correct
\xca\xed/xca\xed/xca\xed/xca\xed/xca\xed For example: Write a picture description here
You need to redefine key
@BeanpublicRedisTemplateredisTemplate(RedisConnectionFactory factory){RedisTemplate redisTemplate =newRedisTemplate(); redisTemplate.setConnectionFactory(factory);
// Key serialization; (otherwise garbled;) , but if the method has a non-string type such as Long, a conversion error will be reported.
// The ObjectRedisSerializer can be configured without your own key generation policy
/ / or JdkSerializationRedisSerializer serialization way;
RedisSerializer redisSerializer =newStringRedisSerializer(); // The Long type should not have an exception message; redisTemplate.setKeySerializer(redisSerializer); redisTemplate.setHashKeySerializer(redisSerializer); returnredisTemplate; }
The complete code: packagecn XXT. Word. Analysis. The service; importcn.xxt.ssm.commons.exception.BizException; importcn.xxt.ssm.commons.json.JacksonJsonUtil; importcn.xxt.word.analysis.pojo.bo.QuestCacheBO; importcn.xxt.word.analysis.pojo.bo.ResourceCacheBO; importcom.alibaba.fastjson.JSONArray; importorg.springframework.beans.factory.InitializingBean; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.redis.core.StringRedisTemplate; importorg.springframework.data.redis.core.ValueOperations; importorg.springframework.data.redis.serializer.RedisSerializer; importorg.springframework.data.redis.serializer.StringRedisSerializer; importorg.springframework.stereotype.Service; importorg.springframework.util.CollectionUtils; importorg.springframework.util.StringUtils; importjava.util.ArrayList; importjava.util.Collections; importjava.util.List; importjava.util.Set; / * * * redis buffer action class * / @ ServicepublicclassRedisCacheServiceimplementsInitializingBean {privateValueOperations valueOperations; @AutowiredprivateStringRedisTemplate redisTemplate; @SuppressWarnings("unchecked")@OverridepublicvoidafterPropertiesSet()throwsException{RedisSerializer redisSerializer =newStringRedisSerializer(); // The Long type should not have an exception message; redisTemplate.setKeySerializer(redisSerializer); redisTemplate.setHashKeySerializer(redisSerializer); valueOperations = redisTemplate.opsForValue(); }/** * cache resource * @paramKey * @paramResourcecachebolist */publicvoidcacheResource(String key, List<ResourceCacheBO> resourceCacheBOList){collectionUtils.isEmpty (resourceCacheBOList); {thrownewBizException(1," parameter error "); } / / cache the String resourceCacheValue = JacksonJsonUtil. ObjectToString (resourceCacheBOList); valueOperations.set(key, resourceCacheValue); } / * * * from the cache access to resources information * @ @ return paramkey * * / / / TODO under test publicListgetCacheResource (String key) {Set < String > keys = redisTemplate.keys(key); if(CollectionUtils.isEmpty(keys)) {returnnewArrayList<>(); }List resourceCacheBOList =newArrayList<>(); for(String accurateKey : keys) { String cacheValue = valueOperations.get(accurateKey); List<ResourceCacheBO> sub = JSONArray.parseArray(cacheValue, ResourceCacheBO.class); resourceCacheBOList.addAll(sub); }returnresourceCacheBOList; } / cache key code * * * * * @ @ paramkey return * / publicvoidcacheKeyWordCode (String key, String code) {/ / check if parameters (StringUtils. IsEmpty (key) | | StringUtils. IsEmpty (code)) {thrownewBizException (1, "parameter is wrong"); }// Cache valueoperations.set (key, code); } / access to key code * * * * * @ @ paramkey return * / publicStringgetKeyWordCode (String key) {String keyWordCode = valueOperations.get(key); if(StringUtils.isEmpty(keyWordCode)) {returnnull; }else{returnkeyWordCode; }} / batch access to key code * * * * * @ @ paramkeys return * / publicListbatchGetKeyWordCode (a List < String > keys) {a List < String > codes = valueOperations.multiGet(keys); if(CollectionUtils.isEmpty(codes)) {returnnewArrayList<>(); }else{codes.removeAll(Collections.singleton(null)); returncodes; }}
Conclusion:
If your Redis database is already storing string data or if the data you want to access is string data, you can just use StringRedisTemplate,
However, if your data is a complex object type and you don’t want to do any data conversion when fetching an object directly from Redis, then using RedisTemplate is a better choice.