项目修炼之路(5)高并发下优化Redis缓存效率

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介:

最近,公司给了个优化任务,某个耗时的操作,在百亿的交易额下,处理异常缓慢,需要优化,以为每日发息做准备,在这里给大家介绍下我的优化思路,共同探讨下:


代码逻辑:

        通过用户id获取用户所在区域id,每次批量处理1千个用户,起20个线程处理。


第一步,加缓存

通过用户id获取用户所在区域id分两步实现(代码中已经标红),第一步通过用户获取城市id,第二部通过城市id获取区域id,使用上篇博客介绍的方法(项目修炼之路(4)aop+注解的自动缓存),给两个方法加入Redis缓存。

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
27
28
29
30
31
32
33
34
@Override  
     public  PublicResult<HashMap<Integer, Integer>> getUserAreaFranchiseeIDS(List<Integer> uids) {  
         PublicResult<HashMap<Integer, Integer>> result =  new  PublicResult<HashMap<Integer, Integer>>();  
         HashMap<Integer, Integer> resultMap =  new  HashMap<Integer, Integer>();  
   
         long  time;  
         for (Integer uid :uids){  
             Integer areaId = Integer.valueOf( 0 );  
             try  {  
                 time=System.currentTimeMillis();  
                 UserAreaFranchisee area =getUserAreaFranchisee(uid).getResult();  
                 LOGGER.info( "=getUserAreaFranchiseeIDS=>--.uid:[" +uid+ "].[get -- wmpsDayInterChange]getUserAreaFranchisee() -------------spen time:"  + (System.currentTimeMillis()-time));  
                 time=System.currentTimeMillis();  
                 int  id =  0 ;  
                 if  (area !=  null  && area.getCityid() !=  null  && area.getCityid().intValue() >  0 ) {  
                     id = area.getCityid().intValue();  
                      tpr = logicTongchengAreaService.getTongchengArea(Integer.valueOf(id));  
                     if  (tpr !=  null  && tpr.isSuccess() && tpr.getResult() !=  null  && tpr.getResult().getId() !=  null  && tpr.getResult().getId() >  0 ) {  
                         areaId = tpr.getResult().getId();  
                     }  
                 }  
                 LOGGER.info( "=getUserAreaFranchiseeIDS=>--..uid:[" +uid+ "].[get -- wmpsDayInterChange]getLogicTongchengAreaService() -------------spen time:"  + (System.currentTimeMillis()-time));  
   
             } catch  (Exception e){  
                 LOGGER.error( "=getUserAreaFranchiseeIDS=>" ,e);  
             }  
             resultMap.put(uid,areaId);  
         }  
   
   
         result.setSuccess( true );  
         result.setResult(resultMap);  
         return  result;  
     }

第二步,合并结果

问题:加入缓存后,发现,当访问频繁时,两次访问加入的缓存不合理:1,value为对象,给每次取值增加反序列化过程,实际只需id即可;2,两次操作,最终只需一个结果,造成资源浪费。

优化后:二次缓存变为一次缓存,key与value均为简单string与Intege

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override  
     public  PublicResult<String> getUserAreaFranchiseeIDS(ArrayList<Integer> uids) {  
         PublicResult<String> result =  new  PublicResult<String>();  
         HashMap<Integer, Integer> resultMap =  new  HashMap<Integer, Integer>();  
         long  time;  
         for (Integer uid :uids){  
             Integer areaId = Integer.valueOf( 0 );  
             try  {  
                 time=System.currentTimeMillis();  
                 areaId = userAreaFranchiseeService.getUserAreaIdByUid(uid);  
                 LOGGER.info( "=getUserAreaFranchiseeIDS=>--.uid:["  + uid +  "].[get -- wmpsDayInterChange]getUserAreaIdByUid() -------------spen time:"  + (System.currentTimeMillis() - time));  
             } catch  (Exception e){  
                 LOGGER.error( "=getUserAreaFranchiseeIDS=>" ,e);  
             }  
             resultMap.put(uid,areaId);  
         }  
         result.setSuccess( true );  
         result.setResult(JSON.toJSONString(resultMap));  
         return  result;  
     }

第三步:批量读取

问题:redis为单线程,批量数据访问时,单个从redis拿数据的时间被延长,造成时间上的浪费,而且,浪费在网络上的时间比读数据时间要长

优化后:批量从redis获取一次获取,多次io改为一次io,拿不到的数据,才从数据库中读取,同时缓存到redis。

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
27
28
29
30
31
@Override  
     public  PublicResult<String> getUserAreaFranchiseeIDS(ArrayList<Integer> uids) {  
         PublicResult<String> result =  new  PublicResult<String>();  
         HashMap<Integer, Integer> resultMap =  new  HashMap<Integer, Integer>();  
         long  time;  
         ArrayList<String> uidKeys =  new  ArrayList<String>();  
         for ( int  i= 0 ;i<uids.size();i++){  
             uidKeys.add(i,RedisKeyUtils.USER_AREA_ID+ uids.get(i));  
         }  
         List<Integer> listAreas = RedisUtils.mget(uidKeys.toArray(),Integer. class );  
         for ( int  i= 0  ;i<uids.size();i++){  
             Integer uid = uids.get(i);  
             Integer areaId = Integer.valueOf( 0 );  
             if (listAreas.get(i)== null ){  
                 try  {  
                     time=System.currentTimeMillis();  
                     areaId = userAreaFranchiseeService.getUserAreaIdByUid(uid);  
                     LOGGER.info( "=getUserAreaFranchiseeIDS=>--.uid:["  + uid +  "].[get -- wmpsDayInterChange]getUserAreaIdByUid() -------------spen time:"  + (System.currentTimeMillis() - time));  
   
                 } catch  (Exception e){  
                     LOGGER.error( "=getUserAreaFranchiseeIDS=>error uid:[" +uid+ "]" ,e);  
                 }  
                 listAreas.set(i,areaId);  
             }  
             areaId = listAreas.get(i);  
             resultMap.put(uid,areaId);  
         }  
         result.setSuccess( true );  
         result.setResult(JSON.toJSONString(resultMap));  
         return  result;  
     }

第四步:批量添加

问题:设置缓存周期后,每隔一段时间,读取数据几乎全从数据库读取,加上增加到redis的时间,会造成周期性读取缓慢。

优化后:时间限制拉长,判断是否能从redis获取一半的数据,如果不能,批量将数据缓存到redis(一次io),再走逻辑

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@Override  
     public  PublicResult<String> getUserAreaFranchiseeIDS(ArrayList<Integer> uids) {  
         PublicResult<String> result =  new  PublicResult<String>();  
         HashMap<Integer, Integer> resultMap =  new  HashMap<Integer, Integer>();  
         long  time;  
         ArrayList<String> uidKeys =  new  ArrayList<String>();  
         for ( int  i= 0 ;i<uids.size();i++){  
             uidKeys.add(i,RedisKeyUtils.USER_AREA_ID+ uids.get(i));  
         }  
         List<Integer> listAreas = RedisUtils.mget(uidKeys.toArray(),Integer. class );  
   
         try  {  
             if  (ListUtil.countNullNumber(listAreas) > listAreas.size() /  2 ) {  
                 initRedisByUids(uids);  
                 listAreas = RedisUtils.mget(uidKeys.toArray(), Integer. class );  
             }  
         } catch  (Exception e){  
             LOGGER.error( "=getUserAreaFranchiseeIDS=>initRedisByUids error" ,e);  
         }  
   
         for ( int  i= 0  ;i<uids.size();i++){  
             Integer uid = uids.get(i);  
             Integer areaId = Integer.valueOf( 0 );  
             if (listAreas.get(i)== null ){  
                 try  {  
                     time=System.currentTimeMillis();  
                     areaId = userAreaFranchiseeService.getUserAreaIdByUid(uid);  
                     LOGGER.info( "=getUserAreaFranchiseeIDS=>--.uid:["  + uid +  "].[get -- wmpsDayInterChange]getUserAreaIdByUid() -------------spen time:"  + (System.currentTimeMillis() - time));  
   
                 } catch  (Exception e){  
                     LOGGER.error( "=getUserAreaFranchiseeIDS=>error uid:[" +uid+ "]" ,e);  
                 }  
                 listAreas.set(i,areaId);  
             }  
             areaId = listAreas.get(i);  
             resultMap.put(uid,areaId);  
         }  
         result.setSuccess( true );  
         result.setResult(JSON.toJSONString(resultMap));  
         return  result;  
     }  
   
     private  boolean  initRedisByUids(ArrayList<Integer> uids){  
         boolean  isSuccess =  false ;  
         HashMap<String, Integer> resultMap = null ;  
         try  {  
             resultMap = ListUtil.getMaxAndMinInterger(uids);  
             if (resultMap!= null  && !resultMap.isEmpty()){  
   
                 List<UserAreaUidVo> listResult = userAreaFranchiseeService.getUserAreaIdPageByUid(resultMap.get(ListUtil.minNumKey), resultMap.get(ListUtil.maxNumKey));  
                 if (listResult!= null  && !listResult.isEmpty()){  
                     HashMap<String ,List> hashMapForUid =uidToRedisKeyAndVlues(listResult);  
                     RedisUtils.mset(hashMapForUid.get(RedisKeys).toArray(),hashMapForUid.get(RedisValues).toArray(),RedisKeyUtils.USER_AREA_ID_TIME);  
                     isSuccess= true ;  
                 }  
             }  
         } catch (Exception e){  
             LOGGER.error( "=initRedisByUids=>" ,e);  
         }  
   
         return  isSuccess;  
     }  
   
     private  HashMap<String ,List> uidToRedisKeyAndVlues(List<UserAreaUidVo> listUserArea){  
         HashMap<String ,List> hashMapForUid =  new  HashMap<String ,List>();  
         List<String> keys =  new  ArrayList<String>(listUserArea.size());  
         List<Integer> values =  new  ArrayList<Integer>(listUserArea.size());  
         for ( int  i= 0 ;i<listUserArea.size();i++){  
             keys.add( RedisKeyUtils.USER_AREA_ID + listUserArea.get(i).getUid());  
             values.add(listUserArea.get(i).getAreaid() ==  null  0  : listUserArea.get(i).getAreaid());  
         }  
         hashMapForUid.put(RedisKeys,keys);  
         hashMapForUid.put(RedisValues,values);  
         return  hashMapForUid;  
     }

总结:

        在工作中,我们会遇到各种难题,实际这些难题,帮助我们提升了自己的解决问题能力外,还帮助我们制造了一种奇妙的东西,叫思路,或者叫框架,就是再有类似问题时,我们会映射过来,我是不是解决过,不仅仅局限在代码端,在生活和处理社会问题时,实际是相通的!

        所以,代码积累的不仅仅是工作经验,还有生活经验!


附录:工具类:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public  class  ListUtil {  
   
     public  static  String maxNumKey = "max" ;  
     public  static  String minNumKey = "min" ;  
     /** 
      * 按照某大小对list分页 
      * @param targe 
      * @param size 
      * @return 
      */  
     public  static  List<List>  splitList(List targe, int  size) {  
         List<List> listArr =  new  ArrayList<List>();  
         //获取被拆分的数组个数  
         int  arrSize = targe.size()%size== 0 ?targe.size()/size:targe.size()/size+ 1 ;  
         for ( int  i= 0 ;i<arrSize;i++) {  
             List  sub =  new  ArrayList();  
             //把指定索引数据放入到list中  
             for ( int  j=i*size;j<=size*(i+ 1 )- 1 ;j++) {  
                 if (j<=targe.size()- 1 ) {  
                     sub.add(targe.get(j));  
                 }  
             }  
             listArr.add(sub);  
         }  
         return  listArr;  
     }  
   
     /** 
      * 统计list中为null的元素个数 
      * @param listTest 
      * @return 
      */  
    public  static  long  countNullNumber(List listTest){  
        long   count= 0 ;  
        for ( int  i= 0 ;i<listTest.size();i++){  
            if (listTest.get(i)== null ){  
                count++;  
            }  
        }  
        return  count;  
    }  
   
     /** 
      * 统计list中为null的元素个数 
      * @param listTest 
      * @return 
      */  
     public  static  HashMap getMaxAndMinInterger(List<Integer> listTest) throws  Exception{  
         if (listTest== null  || listTest.isEmpty()){  
             throw  new  Exception( "=ListUtil.getMaxAndMinInterger=> listTest is null" );  
         }  
         HashMap<String,Integer> result =  new  HashMap<String,Integer>();  
         Integer  maxNum= null ;  
         Integer minNum= null ;  
         for ( int  i= 0 ;i<listTest.size();i++){  
             if (!(listTest.get(i)== null )){  
                 if (maxNum== null ){  
                     maxNum=listTest.get(i);  
                 }  
   
                 if (maxNum<listTest.get(i)){  
                     maxNum=listTest.get(i);  
                 }  
   
                 if (minNum== null ){  
                     minNum=listTest.get(i);  
                 }  
                 if (minNum>listTest.get(i)){  
                     minNum=listTest.get(i);  
                 }  
             }  
         }  
         if (maxNum== null  || minNum ==  null ){  
             throw  new  Exception( "=ListUtil.getMaxAndMinInterger=> listTest is null" );  
         }  
         result.put(maxNumKey,maxNum);  
         result.put(minNumKey,minNum);  
         return  result;  
     }  
   
   
}

























本文转自yunlielai51CTO博客,原文链接:http://blog.51cto.com/4925054/1920485 ,如需转载请自行联系原作者

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
6天前
|
缓存 NoSQL Java
Redis应用—8.相关的缓存框架
本文介绍了Ehcache和Guava Cache两个缓存框架及其使用方法,以及如何自定义缓存。主要内容包括:Ehcache缓存框架、Guava Cache缓存框架、自定义缓存。总结:Ehcache适合用作本地缓存或与Redis结合使用,Guava Cache则提供了更灵活的缓存管理和更高的并发性能。自定义缓存可以根据具体需求选择不同的数据结构和引用类型来实现特定的缓存策略。
Redis应用—8.相关的缓存框架
|
2天前
|
存储 缓存 NoSQL
Redis缓存设计与性能优化
Redis缓存设计与性能优化涵盖缓存穿透、击穿、雪崩及热点key重建等问题。针对缓存穿透,可采用缓存空对象或布隆过滤器;缓存击穿通过随机设置过期时间避免集中失效;缓存雪崩需确保高可用性并使用限流熔断组件;热点key重建利用互斥锁防止大量线程同时操作。此外,开发规范强调键值设计、命令使用和客户端配置优化,如避免bigkey、合理使用批量操作和连接池管理。系统内核参数如vm.swappiness、vm.overcommit_memory及文件句柄数的优化也至关重要。慢查询日志帮助监控性能瓶颈。
27 9
|
1月前
|
缓存 NoSQL 中间件
Redis,分布式缓存演化之路
本文介绍了基于Redis的分布式缓存演化,探讨了分布式锁和缓存一致性问题及其解决方案。首先分析了本地缓存和分布式缓存的区别与优劣,接着深入讲解了分布式远程缓存带来的并发、缓存失效(穿透、雪崩、击穿)等问题及应对策略。文章还详细描述了如何使用Redis实现分布式锁,确保高并发场景下的数据一致性和系统稳定性。最后,通过双写模式和失效模式讨论了缓存一致性问题,并提出了多种解决方案,如引入Canal中间件等。希望这些内容能为读者在设计分布式缓存系统时提供有价值的参考。感谢您的阅读!
130 6
Redis,分布式缓存演化之路
|
2月前
|
缓存 NoSQL 架构师
Redis批量查询的四种技巧,应对高并发场景的利器!
在高并发场景下,巧妙地利用缓存批量查询技巧能够显著提高系统性能。 在笔者看来,熟练掌握细粒度的缓存使用是每位架构师必备的技能。因此,在本文中,我们将深入探讨 Redis 中批量查询的一些技巧,希望能够给你带来一些启发。
192 23
Redis批量查询的四种技巧,应对高并发场景的利器!
|
16天前
|
存储 缓存 小程序
微信小程序数据缓存与本地存储:优化用户体验
本文深入探讨微信小程序的数据缓存与本地存储,介绍其意义、机制及应用场景。通过合理使用内存和本地缓存,可减少网络请求、提升加载速度和用户体验。文中详细讲解了常用缓存API的使用方法,并通过一个新闻列表案例展示了缓存的实际应用。最后提醒开发者注意缓存大小限制、时效性和清理,以确保最佳性能。
|
2月前
|
存储 缓存 NoSQL
云端问道21期方案教学-应对高并发,利用云数据库 Tair(兼容 Redis®*)缓存实现极速响应
云端问道21期方案教学-应对高并发,利用云数据库 Tair(兼容 Redis®*)缓存实现极速响应
|
3月前
|
存储 缓存 NoSQL
解决Redis缓存数据类型丢失问题
解决Redis缓存数据类型丢失问题
207 85
|
5月前
|
消息中间件 缓存 NoSQL
Redis 是一个高性能的键值对存储系统,常用于缓存、消息队列和会话管理等场景。
【10月更文挑战第4天】Redis 是一个高性能的键值对存储系统,常用于缓存、消息队列和会话管理等场景。随着数据增长,有时需要将 Redis 数据导出以进行分析、备份或迁移。本文详细介绍几种导出方法:1)使用 Redis 命令与重定向;2)利用 Redis 的 RDB 和 AOF 持久化功能;3)借助第三方工具如 `redis-dump`。每种方法均附有示例代码,帮助你轻松完成数据导出任务。无论数据量大小,总有一款适合你。
108 6
|
2月前
|
缓存 NoSQL 关系型数据库
云端问道21期实操教学-应对高并发,利用云数据库 Tair(兼容 Redis®)缓存实现极速响应
本文介绍了如何通过云端问道21期实操教学,利用云数据库 Tair(兼容 Redis®)缓存实现高并发场景下的极速响应。主要内容分为四部分:方案概览、部署准备、一键部署和完成及清理。方案概览中,展示了如何使用 Redis 提升业务性能,降低响应时间;部署准备介绍了账号注册与充值步骤;一键部署详细讲解了创建 ECS、RDS 和 Redis 实例的过程;最后,通过对比测试验证了 Redis 缓存的有效性,并指导用户清理资源以避免额外费用。
|
3月前
|
缓存 监控 NoSQL
Redis经典问题:缓存穿透
本文详细探讨了分布式系统和缓存应用中的经典问题——缓存穿透。缓存穿透是指用户请求的数据在缓存和数据库中都不存在,导致大量请求直接落到数据库上,可能引发数据库崩溃或性能下降。文章介绍了几种有效的解决方案,包括接口层增加校验、缓存空值、使用布隆过滤器、优化数据库查询以及加强监控报警机制。通过这些方法,可以有效缓解缓存穿透对系统的影响,提升系统的稳定性和性能。