0%

redis-管道

redis之管道(Pipelining)

Pipelining: 可以一次性发送多条命令

缺点: 容易造成内存溢出,建议分批发送;中途不能做判断处理。

起一个springboot的项目

pom文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.2.0</version>
</dependency>

application.properity

1
2
3
4
5
6
7
8
9
spring.redis.host=192.168.1.114
spring.redis.database=0
spring.redis.port=6379
spring.redis.password=

spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.min-idle=0

没有使用管道

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 @Autowired
private StringRedisTemplate stringRedisTemplate;

long second1 = DateUtil.currentSeconds();

System.out.println("开始时间(秒)->"+second1);
stringRedisTemplate.execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection stringRedisConnection = (StringRedisConnection)connection;
for (Integer i = 0; i <500 ; i++) {
stringRedisConnection.get(i.toString());
}
return null;
}
});
long second2 = DateUtil.currentSeconds();
System.out.println("结束时间(秒)->"+second2);
System.out.println("花费时间(秒)->"+(second2-second1));
// 控制台打印
开始时间(秒)->1584689346
2020-03-20 15:29:06.526 INFO 67233 --- [ main] io.lettuce.core.EpollProvider : Starting without optional epoll library
2020-03-20 15:29:06.531 INFO 67233 --- [ main] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
结束时间(秒)->1584689357
花费时间(秒)->11

使用管道

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
long second1 = DateUtil.currentSeconds();

System.out.println("开始时间(秒)->"+second1);
List list = stringRedisTemplate.executePipelined(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection stringRedisConnection = (StringRedisConnection) connection;
for (Integer i = 0; i < 10000; i++) {

stringRedisConnection.get(i.toString());

}

return null;
}
});
long second2 = DateUtil.currentSeconds();
System.out.println("结束时间(秒)->"+second2);
System.out.println("花费时间(秒)->"+(second2-second1));

// 控制台打印
开始时间(秒)->1584689499
2020-03-20 15:31:39.604 INFO 67880 --- [ main] io.lettuce.core.EpollProvider : Starting without optional epoll library
2020-03-20 15:31:39.608 INFO 67880 --- [ main] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
结束时间(秒)->1584689506
花费时间(秒)->7

从上面可以看出使用管道查询一万条数据比不使用查询500条数据还要快,

-------------本文结束感谢你的阅读---------