热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java秒杀实战(七)安全优化

转自:https:blog.csdn.netqq_41305266articledetails81174782一、隐藏秒杀地址思路:秒杀开始前,先去请求接口获取秒杀地址1.接口改造

转自:https://blog.csdn.net/qq_41305266/article/details/81174782

一、隐藏秒杀地址

思路:秒杀开始前,先去请求接口获取秒杀地址

1.接口改造,带上PathVariable参数

2.添加生成地址的接口

3.秒杀收到请求,先验证PathVariable

二、数学公式验证码

1.添加生产验证码接口

2.在获取秒杀路径的时候,验证验证码

3.ScriptEngine使用

package com.wings.seckill.controller;

import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wings.seckill.access.AccessLimit;
import com.wings.seckill.domain.SeckillOrder;
import com.wings.seckill.domain.SeckillUser;
import com.wings.seckill.rabbitmq.MQSender;
import com.wings.seckill.rabbitmq.SeckillMessage;
import com.wings.seckill.redis.GoodsKey;
import com.wings.seckill.redis.OrderKey;
import com.wings.seckill.redis.RedisService;
import com.wings.seckill.redis.SeckillKey;
import com.wings.seckill.result.CodeMsg;
import com.wings.seckill.result.Result;
import com.wings.seckill.service.GoodsService;
import com.wings.seckill.service.OrderService;
import com.wings.seckill.service.SeckillService;
import com.wings.seckill.service.SeckillUserService;
import com.wings.seckill.vo.GoodsVo;

@Controller
@RequestMapping("/seckill")
public class SeckillController implements InitializingBean {

@Autowired
SeckillUserService userService;

@Autowired
RedisService redisService;

@Autowired
GoodsService goodsService;

@Autowired
OrderService orderService;

@Autowired
SeckillService seckillService;

@Autowired
MQSender sender;

private HashMap localOverMap = new HashMap();

@Override
public void afterPropertiesSet() throws Exception {
List goodsList = goodsService.listGoodsVo();
if (goodsList == null) {
return;
}
for (GoodsVo goods : goodsList) {
redisService.set(GoodsKey.getSeckillGoodsStock, "" + goods.getId(), goods.getStockCount());
localOverMap.put(goods.getId(), false);
}

}

@RequestMapping(value = "/{path}/do_seckill", method = RequestMethod.POST)
@ResponseBody
public Result list(Model model, SeckillUser user, @RequestParam("goodsId") long goodsId,
@PathVariable("path") String path) {
model.addAttribute("user", user);
if (user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
// 验证path
boolean check = seckillService.checkPath(user, goodsId, path);
if (!check) {
return Result.error(CodeMsg.REQUEST_ILLEGAL);
}
// 内存标记,减少redis访问
boolean over = localOverMap.get(goodsId);
if (over) {
return Result.error(CodeMsg.SECKill_OVER);
}
// 预减库存
long stock = redisService.decr(GoodsKey.getSeckillGoodsStock, "" + goodsId);
if (stock <0) {
localOverMap.put(goodsId, true);
return Result.error(CodeMsg.SECKill_OVER);
}
// 判断是否已经秒杀到了
SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
if (order != null) {
return Result.error(CodeMsg.REPEATE_SECKILL);
}
// 入队
SeckillMessage mm = new SeckillMessage();
mm.setUser(user);
mm.setGoodsId(goodsId);
sender.sendSeckillMessage(mm);
return Result.success(0);// 排队中

}

@RequestMapping(value = "/reset", method = RequestMethod.GET)
@ResponseBody
public Result reset(Model model) {
List goodsList = goodsService.listGoodsVo();
for (GoodsVo goods : goodsList) {
goods.setStockCount(10);
redisService.set(GoodsKey.getSeckillGoodsStock, "" + goods.getId(), 10);
localOverMap.put(goods.getId(), false);
}
redisService.delete(OrderKey.getSeckillOrderByUidGid);
redisService.delete(SeckillKey.isGoodsOver);
seckillService.reset(goodsList);
return Result.success(true);
}

/**
* orderId:成功 -1:秒杀失败 0: 排队中
*/
@RequestMapping(value = "/result", method = RequestMethod.GET)
@ResponseBody
public Result seckillResult(Model model, SeckillUser user, @RequestParam("goodsId") long goodsId) {
model.addAttribute("user", user);
if (user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
long result = seckillService.getSeckillResult(user.getId(), goodsId);
return Result.success(result);
}

@AccessLimit(secOnds= 5, maxCount = 5, needLogin = true)
@RequestMapping(value = "/path", method = RequestMethod.GET)
@ResponseBody
public Result getSeckillPath(HttpServletRequest request, SeckillUser user,
@RequestParam("goodsId") long goodsId,
@RequestParam(value = "verifyCode", defaultValue = "0") int verifyCode) {
if (user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
boolean check = seckillService.checkVerifyCode(user, goodsId, verifyCode);
if (!check) {
return Result.error(CodeMsg.REQUEST_ILLEGAL);
}
String path = seckillService.createSeckillPath(user, goodsId);
return Result.success(path);
}

@RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
@ResponseBody
public Result getSeckillVerifyCod(HttpServletResponse response, SeckillUser user,
@RequestParam("goodsId") long goodsId) {
if (user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
try {
BufferedImage image = seckillService.createVerifyCode(user, goodsId);
OutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
return null;
} catch (Exception e) {
e.printStackTrace();
return Result.error(CodeMsg.SECKILL_FAIL);
}
}
}
package com.wings.seckill.service;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Random;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wings.seckill.domain.OrderInfo;
import com.wings.seckill.domain.SeckillOrder;
import com.wings.seckill.domain.SeckillUser;
import com.wings.seckill.redis.RedisService;
import com.wings.seckill.redis.SeckillKey;
import com.wings.seckill.util.Md5Util;
import com.wings.seckill.util.UUIDUtil;
import com.wings.seckill.vo.GoodsVo;

@Service
public class SeckillService {

@Autowired
GoodsService goodsService;

@Autowired
OrderService orderService;

@Autowired
RedisService redisService;

@Transactional
public OrderInfo seckill(SeckillUser user, GoodsVo goods) {
// 减库存 下订单 写入秒杀订单
boolean success = goodsService.reduceStock(goods);
if (success) {
// order_info maiosha_order
return orderService.createOrder(user, goods);
} else {
setGoodsOver(goods.getId());
return null;
}
}

public long getSeckillResult(Long userId, long goodsId) {
SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(userId, goodsId);
if (order != null) {// 秒杀成功
return order.getOrderId();
} else {
boolean isOver = getGoodsOver(goodsId);
if (isOver) {
return -1;
} else {
return 0;
}
}
}

private void setGoodsOver(Long goodsId) {
redisService.set(SeckillKey.isGoodsOver, "" + goodsId, true);
}

private boolean getGoodsOver(long goodsId) {
return redisService.exists(SeckillKey.isGoodsOver, "" + goodsId);
}

public void reset(List goodsList) {
goodsService.resetStock(goodsList);
orderService.deleteOrders();
}

public boolean checkPath(SeckillUser user, long goodsId, String path) {
if (user == null || path == null) {
return false;
}
String pathOld = redisService.get(SeckillKey.getSeckillPath, "" + user.getId() + "_" + goodsId, String.class);
return path.equals(pathOld);
}

public String createSeckillPath(SeckillUser user, long goodsId) {
if (user == null || goodsId <= 0) {
return null;
}
String str = Md5Util.md5(UUIDUtil.uuid() + "123456");
redisService.set(SeckillKey.getSeckillPath, "" + user.getId() + "_" + goodsId, str);
return str;
}

public BufferedImage createVerifyCode(SeckillUser user, long goodsId) {
if (user == null || goodsId <= 0) {
return null;
}
int width = 80;
int height = 32;
// create the image
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// set the background color
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
// draw the border
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// create a random instance to generate the codes
Random rdm = new Random();
// make some confusion
for (int i = 0; i <50; i++) {
int x = rdm.nextInt(width);
int y = rdm.nextInt(height);
g.drawOval(x, y, 0, 0);
}
// generate a random code
String verifyCode = generateVerifyCode(rdm);
g.setColor(new Color(0, 100, 0));
g.setFont(new Font("Candara", Font.BOLD, 24));
g.drawString(verifyCode, 8, 24);
g.dispose();
// 把验证码存到redis中
int rnd = calc(verifyCode);
redisService.set(SeckillKey.getSeckillVerifyCode, user.getId() + "," + goodsId, rnd);
// 输出图片
return image;
}

public boolean checkVerifyCode(SeckillUser user, long goodsId, int verifyCode) {
if (user == null || goodsId <= 0) {
return false;
}
Integer codeOld = redisService.get(SeckillKey.getSeckillVerifyCode, user.getId() + "," + goodsId,
Integer.class);
if (codeOld == null || codeOld - verifyCode != 0) {
return false;
}
redisService.delete(SeckillKey.getSeckillVerifyCode, user.getId() + "," + goodsId);
return true;
}

private static int calc(String exp) {
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("Javascript");
return (Integer) engine.eval(exp);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}

private static char[] ops = new char[] { ‘+‘, ‘-‘, ‘*‘ };

/**
* + - *
*/
private String generateVerifyCode(Random rdm) {
int num1 = rdm.nextInt(10);
int num2 = rdm.nextInt(10);
int num3 = rdm.nextInt(10);
char op1 = ops[rdm.nextInt(3)];
char op2 = ops[rdm.nextInt(3)];
String exp = "" + num1 + op1 + num2 + op2 + num3;
return exp;
}
}
























秒杀商品详情


您还没有登录,请登陆后再操作

没有收货地址的提示。。。




























商品名称
商品图片
秒杀开始时间












商品原价
秒杀价
库存数量





 

三、接口防刷

思路:对接口做限流

1.可以用拦截器减少对业务侵入

package com.wings.seckill.access;

import com.wings.seckill.domain.SeckillUser;

public class UserContext {

private static ThreadLocal userHolder = new ThreadLocal();

public static void setUser(SeckillUser user) {
userHolder.set(user);
}

public static SeckillUser getUser() {
return userHolder.get();
}

}
package com.wings.seckill.access;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(METHOD)
public @interface AccessLimit {
int seconds();
int maxCount();
boolean needLogin() default true;
}
package com.wings.seckill.access;

import java.io.OutputStream;

import javax.servlet.http.COOKIE;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.wings.seckill.domain.SeckillUser;
import com.wings.seckill.redis.AccessKey;
import com.wings.seckill.redis.RedisService;
import com.wings.seckill.result.CodeMsg;
import com.wings.seckill.result.Result;
import com.wings.seckill.service.SeckillUserService;

@Service
public class AccessInterceptor extends HandlerInterceptorAdapter{

@Autowired
SeckillUserService userService;

@Autowired
RedisService redisService;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if(handler instanceof HandlerMethod) {
SeckillUser user = getUser(request, response);
UserContext.setUser(user);
HandlerMethod hm = (HandlerMethod)handler;
AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
if(accessLimit == null) {
return true;
}
int secOnds= accessLimit.seconds();
int maxCount = accessLimit.maxCount();
boolean needLogin = accessLimit.needLogin();
String key = request.getRequestURI();
if(needLogin) {
if(user == null) {
render(response, CodeMsg.SESSION_ERROR);
return false;
}
key += "_" + user.getId();
}else {
//do nothing
}
AccessKey ak = AccessKey.withExpire(seconds);
Integer count = redisService.get(ak, key, Integer.class);
if(count == null) {
redisService.set(ak, key, 1);
}else if(count redisService.incr(ak, key);
}else {
render(response, CodeMsg.ACCESS_LIMIT_REACHED);
return false;
}
}
return true;
}

private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
response.setContentType("application/json;charset=UTF-8");
OutputStream out = response.getOutputStream();
String str = JSON.toJSONString(Result.error(cm));
out.write(str.getBytes("UTF-8"));
out.flush();
out.close();
}

private SeckillUser getUser(HttpServletRequest request, HttpServletResponse response) {
String paramToken = request.getParameter(SeckillUserService.COOKIE_TOKEN_NAME);
String COOKIEToken = getCOOKIEValue(request, SeckillUserService.COOKIE_TOKEN_NAME);
if(StringUtils.isEmpty(COOKIEToken) && StringUtils.isEmpty(paramToken)) {
return null;
}
String token = StringUtils.isEmpty(paramToken)?COOKIEToken:paramToken;
return userService.getByToken( token, response);
}

private String getCOOKIEValue(HttpServletRequest request, String cookiName) {
COOKIE[] COOKIEs = request.getCOOKIEs();
if(COOKIEs == null || COOKIEs.length <= 0){
return null;
}
for(COOKIE COOKIE : COOKIEs) {
if(COOKIE.getName().equals(cookiName)) {
return COOKIE.getValue();
}
}
return null;
}

}
package com.wings.seckill.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.wings.seckill.access.AccessInterceptor;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Autowired
private UserArgumentResolver userArgumentResolver;

@Autowired
AccessInterceptor accessInterceptor;

@Override
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(userArgumentResolver);
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(accessInterceptor);
}
}
 

 
---------------------
作者:插上小翅膀的程序猿Wings
来源:CSDN
原文:https://blog.csdn.net/qq_41305266/article/details/81174782
版权声明:本文为博主原创文章,转载请附上博文链接!

Java秒杀实战 (七)安全优化


推荐阅读
  • H5技术实现经典游戏《贪吃蛇》
    本文将分享一个使用HTML5技术实现的经典小游戏——《贪吃蛇》。通过H5技术,我们将探讨如何构建这款游戏的两种主要玩法:积分闯关和无尽模式。 ... [详细]
  • 二维码的实现与应用
    本文介绍了二维码的基本概念、分类及其优缺点,并详细描述了如何使用Java编程语言结合第三方库(如ZXing和qrcode.jar)来实现二维码的生成与解析。 ... [详细]
  • JavaScript 页面卸载事件详解 (onunload)
    当用户从页面离开时(如关闭页面或刷新页面),会触发 onunload 事件,此时可以执行预设的脚本。需要注意的是,不同的浏览器对 onunload 事件的支持程度可能有所不同。 ... [详细]
  • 探索Java 11中的ZGC垃圾收集器
    Java 11引入了一种新的垃圾收集器——ZGC,由Oracle公司研发,旨在支持TB级别的内存容量,并保证极低的暂停时间。本文将探讨ZGC的开发背景、技术特点及其潜在的应用前景。 ... [详细]
  • Android 中的布局方式之线性布局
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 为何Compose与Swarm之后仍有Kubernetes的诞生?
    探讨在已有Compose和Swarm的情况下,Kubernetes是如何以其独特的设计理念和技术优势脱颖而出,成为容器编排领域的领航者。 ... [详细]
  • 在使用 Nginx 作为服务器时,发现 Chrome 能正确从缓存中读取 CSS 和 JS 文件,而 Firefox 却无法有效利用缓存,导致加载速度显著变慢。 ... [详细]
  • 本文介绍了.hbs文件作为Ember.js项目中的视图层,类似于HTML文件的功能,并详细讲解了如何在Ember.js应用中集成Bootstrap框架及其相关组件的方法。 ... [详细]
  • 在日常生活中,支付宝已成为不可或缺的支付工具之一。本文将详细介绍如何通过支付宝实现免费提现,帮助用户更好地管理个人财务,避免不必要的手续费支出。 ... [详细]
  • JUnit下的测试和suite
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 问题描述现在,不管开发一个多大的系统(至少我现在的部门是这样的),都会带一个日志功能;在实际开发过程中 ... [详细]
  • ASP.NET 进度条实现详解
    本文介绍了如何在ASP.NET中使用HTML和JavaScript创建一个动态更新的进度条,并通过Default.aspx页面进行展示。 ... [详细]
  • 本文详细探讨了在Java中如何将图像对象转换为文件和字节数组(Byte[])的技术。虽然网络上存在大量相关资料,但实际操作时仍需注意细节。本文通过使用JMSL 4.0库中的图表对象作为示例,提供了一种实用的方法。 ... [详细]
  • 本文探讨了Node.js后端开发的基础知识,包括模块源码的使用方法、前后端源码的区别以及如何在命令行环境中编译Node.js源代码。 ... [详细]
  • 长期从事ABAP开发工作的专业人士,在面对行业新趋势时,往往需要重新审视自己的发展方向。本文探讨了几位资深专家对ABAP未来走向的看法,以及开发者应如何调整技能以适应新的技术环境。 ... [详细]
author-avatar
qqq
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有