SpringBoot整合Redis管道的示例代碼
執(zhí)行一個(gè)Redis命令,Redis客戶端和Redis服務(wù)器就需要執(zhí)行以下步驟:
客戶端發(fā)送命令到服務(wù)器; 服務(wù)器接受命令請求,執(zhí)行命令,產(chǎn)生相應(yīng)的結(jié)果; 服務(wù)器返回結(jié)果給客戶端; 客戶端接受命令的執(zhí)行結(jié)果,并向用戶展示。Redis命令所消耗的大部分時(shí)間都用在了發(fā)送命令請求和接收命令結(jié)果上面,把任意多條Redis命令請求打包在一起,然后一次性地將它們?nèi)堪l(fā)送給服務(wù)器,而服務(wù)器則會(huì)把所有命令請求都處理完畢之后,一次性地將它們的執(zhí)行結(jié)果全部返回給客戶端。
注意事項(xiàng):
Redis服務(wù)器并不會(huì)限制客戶端在管道中包含的命令數(shù)量,但是卻會(huì)為客戶端的輸入緩沖區(qū)設(shè)置默認(rèn)值為1GB的體積上限:當(dāng)客戶端發(fā)送的數(shù)據(jù)量超過這一限制時(shí),Redis服務(wù)器將強(qiáng)制關(guān)閉該客戶端。因此最好不要一下把大量命令或者一些體積非常龐大的命令放到同一個(gè)管道中執(zhí)行。
除此之外,很多客戶端本身也帶有隱含的緩沖區(qū)大小限制,如果你在使用流水線特性的過程中,發(fā)現(xiàn)某些流水線命令沒有被執(zhí)行,或者流水線返回的結(jié)果不完整,那么很可能就是你的程序觸碰到了客戶端內(nèi)置的緩沖區(qū)大小限制。
2. SpringBoot 整合 Redis 管道實(shí)例SpringBoot 整合 redis 的實(shí)例
使用單個(gè)的 increment 命令,處理 200w個(gè)key:
public class RedisPipelineStudy extends BaseTest { @Autowired private StringRedisTemplate stringRedisTemplate; private static final String PREFIX = 'test0:'; @Test public void test() {StopWatch stopWatch = new StopWatch();stopWatch.start('test0');for (int times = 0; times < 2; times++) { for (int i = 0; i < 1000000; i++) {stringRedisTemplate.opsForValue().increment(PREFIX + i, 1L); }}stopWatch.stop();System.out.println(stopWatch.prettyPrint()); }}
耗時(shí)如下所示:是 12 位 ,單位ns
使用管道 incrBy 處理 200w個(gè)key,每次打包300條命令發(fā)送給服務(wù)器,如下所示:
public class RedisPipelineStudy extends BaseTest { @Autowired private StringRedisTemplate stringRedisTemplate; private static final String PREFIX = 'test1:'; @Test public void test() {StopWatch stopWatch = new StopWatch();stopWatch.start('test1');List<Integer> recordList = new ArrayList<>();for (int times = 0; times < 2; times++) { for (int i = 0; i < 1000000; i++) {try { recordList.add(i); if (recordList.size() > 300) {incrByPipeline(recordList);recordList = new ArrayList<>(); }} catch (Exception e) { System.out.println(e);} } if (!CollectionUtils.isEmpty(recordList)) {incrByPipeline(recordList);recordList = new ArrayList<>(); }}stopWatch.stop();System.out.println(stopWatch.prettyPrint()); } private void incrByPipeline(List<Integer> recordList) {stringRedisTemplate.executePipelined(new RedisCallback<Object>() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException {try { for (Integer record : recordList) {byte[] key = (PREFIX + record).getBytes();connection.incrBy(key, 1); }} catch (Exception e) { System.out.println(e);}return null; }}); }}
耗用時(shí)間: 11 位 ,單位 :ns,是單個(gè)命令耗時(shí)的 1/6。
到此這篇關(guān)于SpringBoot整合Redis管道的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot整合Redis管道內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. HTML DOM setInterval和clearInterval方法案例詳解2. jscript與vbscript 操作XML元素屬性的代碼3. XML在語音合成中的應(yīng)用4. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)5. Vue如何使用ElementUI對表單元素進(jìn)行自定義校驗(yàn)及踩坑6. XML入門的常見問題(三)7. 不要在HTML中濫用div8. XML 非法字符(轉(zhuǎn)義字符)9. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))10. CSS清除浮動(dòng)方法匯總
