環(huán)境:springboot2.3.9.RELEASE + redis3.2.100
Redis是一種基于客戶端-服務(wù)端模型以及請(qǐng)求/響應(yīng)協(xié)議的TCP服務(wù)。這意味著通常情況下一個(gè)請(qǐng)求會(huì)遵循以下步驟:
- 客戶端向服務(wù)端發(fā)送一個(gè)查詢請(qǐng)求,并監(jiān)聽Socket返回,通常是以阻塞模式,等待服務(wù)端響應(yīng)。
- 服務(wù)端處理命令,并將結(jié)果返回給客戶端。
Redis 管道技術(shù)
Redis 管道技術(shù)可以在服務(wù)端未響應(yīng)時(shí),客戶端可以繼續(xù)向服務(wù)端發(fā)送請(qǐng)求,并最終一次性讀取所有服務(wù)端的響應(yīng)。
Redis普通請(qǐng)求模型與管道請(qǐng)求模型對(duì)比
(普通請(qǐng)求模型)來源網(wǎng)絡(luò)
RTT(Round-Trip Time),就是往返時(shí)延,在計(jì)算機(jī)網(wǎng)絡(luò)中它是一個(gè)重要的性能指標(biāo),表示從發(fā)送端發(fā)送數(shù)據(jù)開始,到發(fā)送端收到來自接收端的確認(rèn)(接收端收到數(shù)據(jù)后便立即發(fā)送確認(rèn)),總共經(jīng)歷的時(shí)延。
一般認(rèn)為,單向時(shí)延 = 傳輸時(shí)延t1 + 傳播時(shí)延t2 + 排隊(duì)時(shí)延t3
(管道請(qǐng)求模型)來源網(wǎng)絡(luò)
性能對(duì)比
依賴
<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>
配置文件
spring:
redis:
host: localhost
port: 6379
password: ******
database: 4
lettuce:
pool:
maxActive: 8
maxIdle: 100
minIdle: 10
maxWait: -1
普通方法
@Resource
private StringRedisTemplate stringRedisTemplate ;
public void execNormal() {
long start = System.currentTimeMillis() ;
for (int i = 0; i < 100_000; i++) {
stringRedisTemplate.opsForValue().set("k" + i, "v" + i) ;
}
System.out.println("耗時(shí):" + (System.currentTimeMillis() - start) + " ms") ;
}
測試結(jié)果
總耗時(shí):47秒左右
管道技術(shù)
public void execPipeline() {
long start = System.currentTimeMillis() ;
stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
for (int i = 0; i < 100_000; i++) {
connection.set(("pk" + i).getBytes(), ("pv" + i).getBytes()) ;
}
return null ;
}
}) ;
System.out.println("耗時(shí):" + (System.currentTimeMillis() - start) + " ms") ;
}
測試結(jié)果
耗時(shí):13秒左右
性能提升了3倍多。
完畢!!!
原文地址:https://www.toutiao.com/i6942277978181304863/