經(jīng)過(guò)之前的學(xué)習(xí)積累准给,今天將各部分知識(shí)結(jié)合了下,做了個(gè)Demo,參考《深入淺出SpringBoot2.x》的搶購(gòu)商品Demo做了個(gè)升級(jí)供搀,書中是使用jsp來(lái)做視圖,我將它改變?yōu)槭褂胻hymeleaf模板引擎钠至,因?yàn)檫@樣將前后端分離葛虐,也可以減少一些配置,方便了編寫與查看棉钧;書中在配置Mapper是使用的xml屿脐,我將其修改為注解,我感覺這樣更直觀宪卿,xml寫法的信噪比太低了(ps:學(xué)通信的嘛:))的诵,好多無(wú)效信息,看的比較煩佑钾。下面是整個(gè)Demo的介紹:
1西疤、數(shù)據(jù)庫(kù)表設(shè)計(jì)
分為兩張表,一張為產(chǎn)品表(t_product)休溶,一張為購(gòu)買信息表(t_purchase_record):
[圖片上傳失敗...(image-bf4dee-1558966758263)]
CREATE TABLE `t_product` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`product_name` varchar(60) NOT NULL,
`stock` int(10) NOT NULL,
`price` decimal(16,2) NOT NULL,
`version` int(10) NOT NULL DEFAULT '0',
`note` varchar(256) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `t_purchase_record` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`user_id` int(12) NOT NULL,
`product_id` int(12) NOT NULL,
`price` decimal(16,2) NOT NULL,
`quantity` int(12) NOT NULL,
`sum` decimal(16,2) NOT NULL,
`purchase_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`note` varchar(512) DEFAULT NULL,
PRIMARY KEY (`id`)
);
2代赁、創(chuàng)建POJO扰她,實(shí)體類對(duì)象
@Alias("product")
public class ProductPo implements Serializable{
private Long id;
private String productName;
private int stock;
private double price;
private int version;
private String note;
/*Getter and Setter*/
}
@Alias("purchaseRecord")
public class PurchaseRecordPo implements Serializable {
private Long id;
private Long userId;
private Long productId;
private double price;
private int quantity;
private double sum;
private Timestamp purchaseTime;
private String note;
/*Getter and Setter*/
}
3、持久層芭碍,Mybatis接口定義徒役,使用注解方法生成Mapper映射
@Mapper
public interface ProductMapper {
@Select("SELECT id, product_name as productName, stock, price, version, note FROM t_product where id=#{id}")
ProductPo getProduct(Long id);
@Update("UPDATE t_product SET stock = stock - #{quantity} WHERE id = #{id} ")
int decreaseProduct(@Param("id") Long id, @Param("quantity") int quantity);
}
這里之前@Param沒寫,導(dǎo)致請(qǐng)求/test時(shí)無(wú)法獲取到quantity的值窖壕,調(diào)試了好久忧勿,最后鎖定在初始化購(gòu)買記錄時(shí)quantity的值無(wú)法傳給SQL語(yǔ)句,便去查看Mapper文件中的SQL有沒有寫正確瞻讽,一看也沒寫錯(cuò)啊鸳吸,后來(lái)看到書上他使用了@Param來(lái)標(biāo)注參數(shù),一查才發(fā)現(xiàn)卸夕,當(dāng)需要傳遞多個(gè)參數(shù)給MyBatis時(shí)层释,需要用@Param來(lái)標(biāo)注。
@Mapper
public interface PurchaseRecordMapper {
@Insert("insert into t_purchase_record(\n" +
" user_id,product_id,price,quantity,sum,purchase_date,note)\n" +
" values(#{userId},#{productId},#{price},#{quantity},#{sum},now(),#{note})")
int insertPurchaseRecord(PurchaseRecordPo pr);
}
4快集、使用Spring開發(fā)業(yè)務(wù)層
public interface PurchaseService {
/*
* 處理購(gòu)買業(yè)務(wù)
* @param userId: 用戶編號(hào)
* @param productId: 產(chǎn)品編號(hào)
* @param quantity: 購(gòu)買數(shù)量
* @return 成功 or 失敗
* */
public boolean purchase(Long userId, Long productId, int quantity);
}
@Service
public class PurchaseServiceImpl implements PurchaseService {
@Autowired
private ProductMapper productMapper = null;
@Autowired
private PurchaseRecordMapper purchaseRecordMapper = null;
@Override
// 啟動(dòng)Spring數(shù)據(jù)庫(kù)事務(wù)機(jī)制
@Transactional
public boolean purchase(Long userId, Long productId, int quantity) {
// 獲取產(chǎn)品
ProductPo product = productMapper.getProduct(productId);
// 比較庫(kù)存和購(gòu)買數(shù)量
if (product.getStock() < quantity) {
// 庫(kù)存不足
return false;
}
// 扣減庫(kù)存
productMapper.decreaseProduct(productId, quantity);
// 初始化購(gòu)買記錄
PurchaseRecordPo pr = this.initPurchaseRecord(userId, product, quantity);
// 插入購(gòu)買記錄
purchaseRecordMapper.insertPurchaseRecord(pr);
return true;
}
private PurchaseRecordPo initPurchaseRecord(Long userId, ProductPo product, int quantity) {
PurchaseRecordPo pr = new PurchaseRecordPo();
pr.setNote("購(gòu)買日志贡羔,時(shí)間:" + System.currentTimeMillis());
pr.setPrice(product.getPrice());
pr.setProductId(product.getId());
pr.setQuantity(quantity);
double sum = product.getPrice() * quantity;
pr.setSum(sum);
pr.setUserId(userId);
return pr;
}
}
5、控制層以及HTML頁(yè)面
@RestController
public class PurchaseController {
@Autowired
PurchaseService purchaseService = null;
@GetMapping("/test")
public ModelAndView testPage(){
ModelAndView mv = new ModelAndView("test");
return mv;
}
@PostMapping("/purchase")
public Result purchase(Long userId, Long productId, Integer quantity){
boolean success = purchaseService.purchase(userId, productId, quantity);
String message = success?"搶購(gòu)成功":"搶購(gòu)失敗";
Result result = new Result(success, message);
return result;
}
class Result {
private boolean success = false;
private String message;
public Result(){};
public Result(Boolean success, String message){
this.success = success;
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript"
src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var params = {
userId : 1,
productId : 1,
quantity : 2
};
// 通過(guò)POST請(qǐng)求后端
$.post("./purchase", params, function(result) {
alert(result.message);
});
</script>
</head>
<body>
<h1>搶購(gòu)產(chǎn)品測(cè)試</h1>
</body>
</html>
6个初、pom.xml以及application.properties設(shè)置
在pom.xml中添加web, Mybatis, MySQL, thymeleaf的相關(guān)依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mybatis 依賴 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- ThymeLeaf 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mysql 依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
# 數(shù)據(jù)庫(kù)配置
spring.datasource.url= jdbc:mysql://localhost:3306/shopping?serverTimezone=UCT
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.tomcat.max-idle=10
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.initial-size=5
# 事務(wù)的隔離級(jí)別設(shè)置為 讀寫提交
spring.datasource.tomcat.default-transaction-isolation=2
mybatis.type-aliases-package=com.wayne.springboot.pojo
7乖寒、運(yùn)行測(cè)試
啟動(dòng)項(xiàng)目后在在瀏覽器輸入localhost:8080/test,便可以執(zhí)行一次購(gòu)買院溺,在數(shù)據(jù)庫(kù)的t_product表中會(huì)將產(chǎn)品庫(kù)存減去所購(gòu)數(shù)量楣嘁,如果數(shù)量不夠的話,就購(gòu)買失敗珍逸,如果數(shù)量足夠的話就購(gòu)買成功逐虚,并向t_purchase_record表中插入一條購(gòu)買記錄。
下一篇來(lái)介紹如何應(yīng)對(duì)高并發(fā):使用悲觀鎖谆膳,樂觀鎖叭爱,以及Redis來(lái)提高高并發(fā)能力。