Spring中Redis multiGet方法报错求助:参数类型不匹配问题
Hey there! Let's break down why you're hitting that type mismatch error with Redis's multiGet method in Spring, and how to fix it quickly.
The Root Cause
Your error happens because the multiGet method expects its second parameter (or the only parameter, depending on the overload) to be a Collection type (like List<String>, Set<String>, etc.), but you're passing individual String values directly.
Unlike the get method (which takes a single key), multiGet is designed for batch queries—so it needs a collection of keys instead of separate arguments.
What the Correct Method Signature Looks Like
For reference, here's the standard method signature from Spring Data Redis's StringRedisTemplate (or generic RedisTemplate):
// Basic overload: takes a collection of keys List<String> multiGet(Collection<String> keys); // Overload with a key prefix (if you're using prefixes for keys) List<String> multiGet(Object keyPrefix, Collection<String> keys);
Step-by-Step Fix
- Create a collection of your target keys
Use aList(most common) or any otherCollectionimplementation to hold all the keys you want to query. - Pass this collection to
multiGet
Here's a working example controller code snippet:
@RestController @RequestMapping("/redis") public class RedisController { @Autowired private StringRedisTemplate stringRedisTemplate; // Working single-key get method @GetMapping("/get/{key}") public String getValue(@PathVariable String key) { return stringRedisTemplate.opsForValue().get(key); } // Fixed multiGet method @GetMapping("/multi-get") public List<String> getMultipleValues(@RequestParam List<String> keys) { // Pass the collection directly to multiGet return stringRedisTemplate.opsForValue().multiGet(keys); } // If you're using a key prefix (optional) @GetMapping("/multi-get-with-prefix") public List<String> getMultipleValuesWithPrefix(@RequestParam List<String> keys) { String prefix = "user:"; // Use the overload with prefix + keys collection return stringRedisTemplate.opsForValue().multiGet(prefix, keys); } }
Quick Notes
- If some keys don't exist in Redis, the returned
Listwill havenullvalues at those positions—make sure to handle null checks in your code to avoid NPEs. - You can use any
Collection(likeHashSet) instead ofList, butListis preferred if you care about the order of returned values matching your input keys.
内容的提问来源于stack exchange,提问作者Ruchita J

