当前位置: 首页 > news >正文

网站建设发布实训总结简单的静态网页代码

网站建设发布实训总结,简单的静态网页代码,大宗交易平台,最美情侣免费观看一、业务背景有些业务请求#xff0c;属于耗时操作#xff0c;需要加锁#xff0c;防止后续的并发操作#xff0c;同时对数据库的数据进行操作#xff0c;需要避免对之前的业务造成影响。二、分析流程使用 Redis 作为分布式锁#xff0c;将锁的状态放到 Redis 统一维护属于耗时操作需要加锁防止后续的并发操作同时对数据库的数据进行操作需要避免对之前的业务造成影响。二、分析流程使用 Redis 作为分布式锁将锁的状态放到 Redis 统一维护解决集群中单机 JVM 信息不互通的问题规定操作顺序保护用户的数据正确。梳理设计流程新建注解 interface在注解里设定入参标志增加 AOP 切点扫描特定注解建立 Aspect 切面任务注册 bean 和拦截特定方法特定方法参数 ProceedingJoinPoint对方法 pjp.proceed() 前后进行拦截切点前进行加锁任务执行后进行删除 key核心步骤加锁、解锁和续时加使用了 RedisTemplate 的 opsForValue.setIfAbsent 方法判断是否有 key设定一个随机数 UUID.random().toString生成一个随机数作为 value。从 redis 中获取锁之后对 key 设定 expire 失效时间到期后自动释放锁。按照这种设计只有第一个成功设定 Key 的请求才能进行后续的数据操作后续其它请求由于无法获得锁资源将会失败结束。超时问题担心 pjp.proceed() 切点执行的方法太耗时导致 Redis 中的 key 由于超时提前释放了。例如线程 A 先获取锁proceed 方法耗时超过了锁超时时间到期释放了锁这时另一个线程 B 成功获取 Redis 锁两个线程同时对同一批数据进行操作导致数据不准确。解决方案增加一个「续时」任务不完成锁不释放维护了一个定时线程池 ScheduledExecutorService每隔 2s 去扫描加入队列中的 Task判断是否失效时间是否快到了公式为【失效时间】 【当前时间】【失效间隔三分之一超时】/*** 线程池每个 JVM 使用一个线程去维护 keyAliveTime定时执行 runnable*/ private static final ScheduledExecutorService SCHEDULER new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern(redisLock-schedule-pool).daemon(true).build()); static {SCHEDULER.scheduleAtFixedRate(() - {// do something to extend time}, 0, 2, TimeUnit.SECONDS); }三、设计方案经过上面的分析设计出了这个方案前面已经说了整体流程这里强调一下几个核心步骤拦截注解 RedisLock获取必要的参数加锁操作续时操作结束业务释放锁四、实操之前也有整理过 AOP 使用方法可以参考一下。相关属性类配置业务属性枚举设定public enum RedisLockTypeEnum {/*** 自定义 key 前缀*/ONE(Business1, Test1),TWO(Business2, Test2);private String code;private String desc;RedisLockTypeEnum(String code, String desc) {this.code code;this.desc desc;}public String getCode() {return code;}public String getDesc() {return desc;}public String getUniqueKey(String key) {return String.format(%s:%s, this.getCode(), key);} }任务队列保存参数public class RedisLockDefinitionHolder {/*** 业务唯一 key*/private String businessKey;/*** 加锁时间 (秒 s)*/private Long lockTime;/*** 上次更新时间ms*/private Long lastModifyTime;/*** 保存当前线程*/private Thread currentTread;/*** 总共尝试次数*/private int tryCount;/*** 当前尝试次数*/private int currentCount;/*** 更新的时间周期毫秒,公式 加锁时间转成毫秒 / 3*/private Long modifyPeriod;public RedisLockDefinitionHolder(String businessKey, Long lockTime, Long lastModifyTime, Thread currentTread, int tryCount) {this.businessKey businessKey;this.lockTime lockTime;this.lastModifyTime lastModifyTime;this.currentTread currentTread;this.tryCount tryCount;this.modifyPeriod lockTime * 1000 / 3;} }设定被拦截的注解名字Retention(RetentionPolicy.RUNTIME) Target({ElementType.METHOD, ElementType.TYPE}) public interface RedisLockAnnotation {/*** 特定参数识别默认取第 0 个下标*/int lockFiled() default 0;/*** 超时重试次数*/int tryCount() default 3;/*** 自定义加锁类型*/RedisLockTypeEnum typeEnum();/*** 释放时间秒 s 单位*/long lockTime() default 30; }核心切面拦截的操作RedisLockAspect.java 该类分成三部分来描述具体作用Pointcut 设定/*** annotation 中的路径表示拦截特定注解*/ Pointcut(annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)) public void redisLockPC() { }Around 前后进行加锁和释放锁前面步骤定义了我们想要拦截的切点下一步就是在切点前后做一些自定义操作Around(value redisLockPC()) public Object around(ProceedingJoinPoint pjp) throws Throwable {// 解析参数Method method resolveMethod(pjp);RedisLockAnnotation annotation method.getAnnotation(RedisLockAnnotation.class);RedisLockTypeEnum typeEnum annotation.typeEnum();Object[] params pjp.getArgs();String ukString params[annotation.lockFiled()].toString();// 省略很多参数校验和判空String businessKey typeEnum.getUniqueKey(ukString);String uniqueValue UUID.randomUUID().toString();// 加锁Object result null;try {boolean isSuccess redisTemplate.opsForValue().setIfAbsent(businessKey, uniqueValue);if (!isSuccess) {throw new Exception(You cant do itbecause another has get the lock -);}redisTemplate.expire(businessKey, annotation.lockTime(), TimeUnit.SECONDS);Thread currentThread Thread.currentThread();// 将本次 Task 信息加入「延时」队列中holderList.add(new RedisLockDefinitionHolder(businessKey, annotation.lockTime(), System.currentTimeMillis(),currentThread, annotation.tryCount()));// 执行业务操作result pjp.proceed();// 线程被中断抛出异常中断此次请求if (currentThread.isInterrupted()) {throw new InterruptedException(You had been interrupted -);}} catch (InterruptedException e ) {log.error(Interrupt exception, rollback transaction, e);throw new Exception(Interrupt exception, please send request again);} catch (Exception e) {log.error(has some error, please check again, e);} finally {// 请求结束后强制删掉 key释放锁redisTemplate.delete(businessKey);log.info(release the lock, businessKey is [ businessKey ]);}return result; }上述流程简单总结一下解析注解参数获取注解值和方法上的参数值redis 加锁并且设置超时时间将本次 Task 信息加入「延时」队列中进行续时方式提前释放锁加了一个线程中断标志结束请求finally 中释放锁续时操作这里用了 ScheduledExecutorService维护了一个线程不断对任务队列中的任务进行判断和延长超时时间// 扫描的任务队列 private static ConcurrentLinkedQueueRedisLockDefinitionHolder holderList new ConcurrentLinkedQueue(); /*** 线程池维护keyAliveTime*/ private static final ScheduledExecutorService SCHEDULER new ScheduledThreadPoolExecutor(1,new BasicThreadFactory.Builder().namingPattern(redisLock-schedule-pool).daemon(true).build()); {// 两秒执行一次「续时」操作SCHEDULER.scheduleAtFixedRate(() - {// 这里记得加 try-catch否者报错后定时任务将不会再执行-IteratorRedisLockDefinitionHolder iterator holderList.iterator();while (iterator.hasNext()) {RedisLockDefinitionHolder holder iterator.next();// 判空if (holder null) {iterator.remove();continue;}// 判断 key 是否还有效无效的话进行移除if (redisTemplate.opsForValue().get(holder.getBusinessKey()) null) {iterator.remove();continue;}// 超时重试次数超过时给线程设定中断if (holder.getCurrentCount() holder.getTryCount()) {holder.getCurrentTread().interrupt();iterator.remove();continue;}// 判断是否进入最后三分之一时间long curTime System.currentTimeMillis();boolean shouldExtend (holder.getLastModifyTime() holder.getModifyPeriod()) curTime;if (shouldExtend) {holder.setLastModifyTime(curTime);redisTemplate.expire(holder.getBusinessKey(), holder.getLockTime(), TimeUnit.SECONDS);log.info(businessKey : [ holder.getBusinessKey() ], try count : holder.getCurrentCount());holder.setCurrentCount(holder.getCurrentCount() 1);}}}, 0, 2, TimeUnit.SECONDS); }这段代码用来实现设计图中虚线框的思想避免一个请求十分耗时导致提前释放了锁。这里加了「线程中断」Thread#interrupt希望超过重试次数后能让线程中断未经严谨测试仅供参考哈哈哈哈不过建议如果遇到这么耗时的请求还是能够从根源上查找分析耗时路径进行业务优化或其它处理避免这些耗时操作。所以记得多打点 Log分析问题时可以更快一点。如何使用SpringBoot AOP 记录操作日志、异常日志五、开始测试在一个入口方法中使用该注解然后在业务中模拟耗时请求使用了 Thread#sleepGetMapping(/testRedisLock) RedisLockAnnotation(typeEnum RedisLockTypeEnum.ONE, lockTime 3) public Book testRedisLock(RequestParam(userId) Long userId) {try {log.info(睡眠执行前);Thread.sleep(10000);log.info(睡眠执行后);} catch (Exception e) {// log errorlog.info(has some error, e);}return null; }使用时在方法上添加该注解然后设定相应参数即可根据 typeEnum 可以区分多种业务限制该业务被同时操作。测试结果2020-04-04 14:55:50.864 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : 睡眠执行前2020-04-04 14:55:52.855 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 02020-04-04 14:55:54.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 12020-04-04 14:55:56.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 22020-04-04 14:55:58.852 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 32020-04-04 14:56:00.857 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : has some errorjava.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) [na:1.8.0_221]我这里测试的是重试次数过多失败的场景如果减少睡眠时间就能让业务正常执行。如果同时请求你将会发现以下错误信息表示我们的锁的确生效了避免了重复请求。六、总结对于耗时业务和核心数据不能让重复的请求同时操作数据避免数据的不正确所以要使用分布式锁来对它们进行保护。再来梳理一下设计流程新建注解 interface在注解里设定入参标志增加 AOP 切点扫描特定注解建立 Aspect 切面任务注册 bean 和拦截特定方法特定方法参数 ProceedingJoinPoint对方法 pjp.proceed() 前后进行拦截切点前进行加锁任务执行后进行删除 key本次学习是通过 Review 小伙伴的代码设计从中了解分布式锁的具体实现仿照他的设计重新写了一份简化版的业务处理。对于之前没考虑到的「续时」操作这里使用了守护线程来定时判断和延长超时时间避免了锁提前释放。于是乎同时回顾了三个知识点1、AOP 的实现和常用方法2、定时线程池 ScheduledExecutorService 的使用和参数含义3、线程 Thread#interrupt 的含义以及用法这个挺有意思的可以深入再学习一下
http://www.hkea.cn/news/14319960/

相关文章:

  • 多用户网站源码电脑传奇网站
  • 免费建自己域名的网站做化验的网站
  • phpcms 网站访问统计seo发包技术教程
  • 模板建站什么意思京能集团在2023年中国企业500强
  • 青岛专业餐饮网站制作c 做特产网站
  • 衡水建立网站wordpress没登录窗口
  • 专门做游轮的网站建设网站公司怎么建站
  • 做网站常用什么软件品牌型网站建设的好处
  • 重庆网站设计公司价格做网站必备的注意事项
  • 无锡网站定制公司什么软件能搜索关键词能快速找到
  • 网站建设与推广是什么一个网站如何进行推广宣传
  • 在哪可以接企业网站建设的活渭南建站
  • 北京大兴做网站公司导购类网站怎么做
  • 网站开发的流程是什么合肥网站制作模板推荐
  • 怎么看网站是用什么系统做的wordpress主题绑定域名
  • 做网站_你的出路在哪里东莞东城网站建设公司
  • 外贸公司怎么做网站百度一下网页版
  • thinkphp做的网站源码口碑好的网站开发公司
  • php后台网站开发教程页面模板生成怎么群发
  • 美橙智能网站eefocus电子工程网
  • 网站制作费用多少公司网站设计 杭州 推荐
  • 汕头论坛建站模板用什么软件做网站最快
  • 建设部网站查不到注册证怎么回事竞价网络推广托管
  • 网站开发广东深圳各大网站制作哪家公司好
  • 网网站开发站制作公司兰州市做网站的企业有哪些
  • 网站开发中应注意哪些问题应用商店正版下载安装
  • seo快速整站上排名教程wordpress连不上数据库
  • 河北网站建站制作天津做网站贵吗
  • 百度一下官方网站农业网站建设的特点是
  • 中国最大的家装网站广告设计是学什么的