1 Introduction
Redis uses API to query data. When it encounters multiple key queries, it will subconsciously use a circular query method.
示例代码:
/**
* 大量key的查询
* @param keys
* @return
*/
@GetMapping("/getKeys")
public List<String> getKeys(String... keys){
List<String> result = new ArrayList<>();
for (String key : keys) {
result.add(redisOperator.get(key));
}
return result;
}
@Component
public class RedisOperator {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 实现命令:GET key,返回 key所关联的字符串值。
*
* @param key
* @return value
*/
public String get(String key) {
return (String)redisTemplate.opsForValue().get(key);
}
}
2 mget batch query
示例代码:
/**
* 批量查询 mget
* @param keys
* @return
*/
@GetMapping("/mget")
public List<String> mget(String... keys){
List<String> keysList = Arrays.asList(keys);
return redisOperator.mget(keysList);
}
@Component
public class RedisOperator {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 批量查询
* 实现命令:MGET key1 key2,返回 多个结果。
*
* @param keys
* @return value
*/
public List<String> mget(List<String> keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
}
3 pipeline
Normal redis obtains data through the key, it needs to establish a connection first, and then return the data.
The pipeline pipeline is equivalent to the nginx keepalive, which is similar to a long connection. Each operation is operated from a pipeline, and the interaction only needs to establish a connection.
示例代码:
/**
* 批量查询 pipeline
* @param keys
* @return
*/
@GetMapping("/batchGet")
public List<Object> batchGet(String... keys){
List<String> keysList = Arrays.asList(keys);
return redisOperator.batchGet(keysList);
}
@Component
public class RedisOperator {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 批量查询 管道 pipeline
*
* @param keys
* @return value
*/
public List<Object> batchGet(List<String> keys) {
// nginx -> keepalive
// redis -> pipeline
List<Object> result = redisTemplate.executePipelined(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection src = (StringRedisConnection) connection;
for (String key : keys) {
src.get(key);
}
return null;
}
});
return result;
}
}
4 Related information
- The blog post is not easy, everyone who has worked so hard to pay attention and praise, thank you