在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1、构建SpringBoot项目搭建名为quickbuy的springboot项目,相关的依赖包如下所示: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.13.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.baizhi</groupId> <artifactId>quickbuy</artifactId> <version>0.0.1-SNAPSHOT</version> <name>quickbuy</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.10</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 引入了Redis、HttpClient等依赖包。 2、启动类package com.baizhi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class QuickbuyApplication { public static void main(String[] args) { SpringApplication.run(QuickbuyApplication.class, args); } } 3、在Controller层里定义秒杀接口@RestController public class QuickBuyController { @Autowired private SellService sellService; @RequestMapping("/quickBuy/{item}/{owner}") public String quickbuy(@PathVariable String item,@PathVariable String owner){ String result=sellService.quickBuy(item,owner); if(!result.equals("0")){ return owner+"success"; }else{ return owner+"fail"; } } }
4、在Service层里通过lua脚本实现秒杀效果package com.baizhi.service; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.ReturnType; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class SellService { @Resource private RedisTemplate redisTemplate; public String quickBuy(String item, String owner) { //用lua脚本实现秒杀 String luaScript="local owner=ARGV[1]\n" + "local item=KEYS[1] \n" + "local leftNum=tonumber(redis.call('get',item)) \n" + "if(leftNum>=1)\n" + "then redis.call('decrby',item,1)\n" + "redis.call('rpush','ownerList',owner)\n" + "return 1 \n" + "else \n" + "return 0 \n" + "end\n" + "\n"; String key=item; String args=owner; DefaultRedisScript<String> redisScript=new DefaultRedisScript<String>(); redisScript.setScriptText(luaScript); //调用lua脚本,请注意传入的参数 Object luaResult=redisTemplate.execute((RedisConnection connection)->connection.eval( redisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 1, key.getBytes(), args.getBytes() )); //根据lua脚本的执行情况返回结果 return luaResult.toString(); } } 对lua脚本的解释如下:
在调用redisTemplate.execute方法执行lua脚本时请注意以下三点:
5、配置redis连接参数application.properties server.port=8081 spring.redis.host=192.168.159.22 spring.redis.port=6379 6、演示秒杀效果6.1 准备redis环境我用的刚搭建的redis主从复制集群,一主二从 设置10个商品 6.2 启动项目 在浏览器访问
进入redis查看
发现商品数量变成了9,且能看到秒杀成功的用户列表。 6.3 多线程形式发起秒杀请求QuickBuyClients.java package com.baizhi.client; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class QuickBuyClients extends Thread{ @Override public void run() { QuickBuyUtil.quickBuy(); } public static void main(String[] args) { //开启15个线程,线程数多余秒杀商品数 for(int cnt=0;cnt<15;cnt++){ new QuickBuyClients().start(); } } } //封装秒杀方法的工具类 class QuickBuyUtil{ //在这个方法里,用HttpGet对象发起秒杀请求 public static void quickBuy(){ String user=Thread.currentThread().getName(); CloseableHttpClient httpClient= HttpClientBuilder.create().build(); //创建秒杀Get类型的url请求 HttpGet httpGet=new HttpGet("http://localhost:8081/quickBuy/Computer/"+user); //得到响应结果 CloseableHttpResponse res=null; try{ res=httpClient.execute(httpGet); HttpEntity responseEntity=res.getEntity(); if(res.getStatusLine().equals("200")&&responseEntity!=null){ System.out.println("秒杀结果:"+ EntityUtils.toString(responseEntity)); } }catch (ClientProtocolException e){ e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); }finally { try{ //回收http连接资源 if(httpClient!=null){ httpClient.close(); } if(res!=null){ res.close(); } }catch (Exception e){ e.printStackTrace(); } } } } 先重新设置商品数量为10 启动上面的程序 可以看到,15个线程秒杀商品,最终成功的只有10个。 到此这篇关于Redis结合SpringBoot的秒杀案例的文章就介绍到这了,更多相关Redis结合SpringBoot秒杀内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论