提示:想要了解微服务的点击上一篇博客–>微服务介绍
SpringCloud 介绍点击–>Spring Cloud快速了解入门
1. 案例准备
电商系统:搭建用户微服务,商品微服务,订单微服务
1.1 技术选型maven:3.5+
数据库:mysql 5.7
持久层:MybatisPlus
其他:Spring Cloud Alibaba
1.2 模块设计父工程:shop-parent
用户微服务:shop-user
商品微服务:shop-goods
订单微服务: shop-order
公共服务: shop-common
应用服务:shop-app
1.3 下单场景用户下单,会涉及到用户微服务,商品微服务,订单微服务
1.4 搭建工程 1.4.1 创建父工程–>shop-parent1.4.2 创建common模块–>shop-comment4.0.0 org.example shop-parent pom 1.0-SNAPSHOT shop-user shop-goods shop-order shop-common shop-app 11 11 Hoxton.SR9 2.7.8 4.0.1 2.0.2 2.2.5.RELEASE org.springframework.boot spring-boot-starter-parent 2.2.5.RELEASE com.alibaba.cloud spring-cloud-alibaba-dependencies ${spring.cloud.alibaba} pom import org.springframework.cloud spring-cloud-dependencies ${spring.cloud.version} pom import
shop-parent org.example 1.0-SNAPSHOT 4.0.0 shop-common 11 11 org.projectlombok lombok mysql mysql-connector-java
统一返回类:
package com.yf.common; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Result1.4.3 创建用户微服务–>shop-user 1.4.3.1 XML{ private boolean success; private int code; private String msg; private T data; public static Result success(T data) { return new Result<>(true,200,"success",data); } public static Result fail(int code, String msg) { return new Result<>( true,code,msg,null); } }
1.4.3.2 启动类shop-parent org.example 1.0-SNAPSHOT 4.0.0 shop-user 11 11 org.springframework.boot spring-boot-starter-web org.example shop-common 1.0-SNAPSHOT com.baomidou mybatis-plus-boot-starter 3.4.3 org.springframework.boot spring-boot-starter-test test
package com.yf.shop.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserApp {
public static void main(String[] args) {
SpringApplication.run(UserApp.class,args);
}
}
1.4.3.3 配置文件
application.yml
spring:
application:
name: shop-user
datasource:
password: root
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
server:
port: 8001
mybatis-plus:
global-config:
db-config:
table-prefix: shop_
1.4.3.4 User表
shop_user表:
CREATE TABLE `shop`.`shop_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `telephone` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `account` decimal(10, 2) NOT NULL COMMENT '账户', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
package com.yf.shop.user.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
//分布式id
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String username;
private String password;
private String telephone;
private BigDecimal account;
}
1.4.4 创建商品微服务–>shop-goods
1.4.4.1 XML
1.4.4.2 启动类shop-parent org.example 1.0-SNAPSHOT 4.0.0 shop-goods 11 11 org.springframework.boot spring-boot-starter-web org.example shop-common 1.0-SNAPSHOT com.baomidou mybatis-plus-boot-starter 3.4.3 org.springframework.boot spring-boot-starter-test test
package com.yf.shop.goods;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GoodsApp {
public static void main(String[] args) {
SpringApplication.run(GoodsApp.class);
}
}
1.4.4.3 配置文件
application.yml
spring:
application:
name: shop-goods
datasource:
password: root
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
server:
port: 8002
mybatis-plus:
global-config:
db-config:
table-prefix: shop_
1.4.4.4 商品表
shop_goods表:
CREATE TABLE `shop`.`shop_goods` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `goods_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '商品名称', `goods_price` decimal(10, 2) NOT NULL COMMENT '商品价格', `goods_stock` int(10) NOT NULL COMMENT '商品库存', `create_time` bigint(20) NOT NULL COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
package com.yf.shop.goods.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class Goods {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String goodsName;
private BigDecimal goodsPrice;
private Integer goodsStock;
private Long createTime;
}
1.4.5 创建订单微服务–>shop-order
1.4.5.1 XML
1.4.5.2 启动类shop-parent org.example 1.0-SNAPSHOT 4.0.0 shop-order 11 11 org.springframework.boot spring-boot-starter-web org.example shop-common 1.0-SNAPSHOT com.baomidou mybatis-plus-boot-starter 3.4.3 org.apache.commons commons-lang3 3.12.0 org.springframework.boot spring-boot-starter-test test
package com.yf.shop.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrderApp {
public static void main(String[] args) {
SpringApplication.run(OrderApp.class,args);
}
}
1.4.5.3 配置文件
application.yml
spring:
application:
name: shop-order
datasource:
password: root
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
server:
port: 8003
mybatis-plus:
global-config:
db-config:
table-prefix: shop_
1.4.5.4 订单表
shop_order表:
CREATE TABLE `shop`.`shop_order` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `order_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `user_id` bigint(20) NOT NULL, `goods_id` bigint(20) NOT NULL, `order_price` decimal(10, 2) NOT NULL, `order_status` tinyint(4) NOT NULL, `pay_status` tinyint(4) NOT NULL, `pay_time` bigint(20) NOT NULL, `create_time` bigint(20) NOT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
package com.yf.shop.order.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class Order {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String orderId;
private Long userId;
private Long goodsId;
private BigDecimal orderPrice;
private Integer orderStatus;
private Integer payStatus;
private Long payTime;
private Long createTime;
}
1.5 业务场景
下单服务:
-
前端传递用户id和商品id
- 判断用户是否存在以及账户是否有足够的金额
- 判断商品是否存在以及库存是否足够
- 生成订单
1.5.1.2 配置文件shop-parent org.example 1.0-SNAPSHOT 4.0.0 shop-app 11 11 org.springframework.boot spring-boot-starter-web org.example shop-common 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-test test
spring:
application:
name: shop-app
server:
port: 8004
1.5.1.3 启动类
package com.yf.shop.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
1.5.2 用户微服务 提供用户查询服务
1.5.2.1 Dao层
package com.yf.shop.user.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.yf.shop.user.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
package com.yf.shop.user.mapper; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.yf.shop.user.pojo.User; public interface UserMapper extends baseMapper1.5.2.2 Service层{ }
package com.yf.shop.user.service;
import com.yf.common.Result;
public interface UserService {
Result findUser(Long id);
}
package com.yf.shop.user.service.impl;
import com.yf.common.Result;
import com.yf.common.user.UserBO;
import com.yf.shop.user.mapper.UserMapper;
import com.yf.shop.user.pojo.User;
import com.yf.shop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
public class UserServiceImp implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Result findUser(Long id) {
User user = userMapper.selectById(id);
if (user == null){
return Result.success(null);
}
UserBO userBO = new UserBO();
userBO.setAccount(user.getAccount());
userBO.setId(user.getId());
return Result.success(userBO);
}
}
common模块下:
package com.yf.common.user;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class UserBO {
private Long id;
private BigDecimal account;
}
1.5.2.3 Controller
package com.yf.shop.user.controller;
import com.yf.common.Result;
import com.yf.shop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("findUser/{id}")
public Result findUser(@PathVariable("id") Long id){
return userService.findUser(id);
}
}
1.5.3 商品微服务,提供商品查询服务
1.5.3.1 Dao层
package com.yf.shop.user.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.yf.shop.goods.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
package com.yf.shop.goods.mapper; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.yf.shop.goods.pojo.Goods; public interface GoodsMapper extends baseMapper1.5.3.2 Service层{ }
package com.yf.shop.goods.service;
import com.yf.common.Result;
public interface GoodsService {
Result findGoodsById(Long id);
}
package com.yf.shop.goods.service.impl;
import com.yf.common.Result;
import com.yf.common.goods.GoodsBO;
import com.yf.shop.goods.mapper.GoodsMapper;
import com.yf.shop.goods.pojo.Goods;
import com.yf.shop.goods.service.GoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
private GoodsMapper goodsMapper;
@Override
public Result findGoodsById(Long id) {
Goods goods = goodsMapper.selectById(id);
GoodsBO goodsBO = new GoodsBO();
BeanUtils.copyProperties(goods,goodsBO);
return Result.success(goodsBO);
}
}
package com.yf.common.goods;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GoodsBO {
private Long id;
private String goodsName;
private BigDecimal goodsPrice;
private Integer goodsStock;
}
1.5.3.3 Controller层
package com.yf.shop.goods.controller;
import com.yf.common.Result;
import com.yf.shop.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("goods")
public class GoodsController {
@Autowired
private GoodsService goodsService;
@GetMapping("findGoods/{id}")
public Result findGoods(@PathVariable("id") Long id){
return goodsService.findGoodsById(id);
}
}
1.5.4 订单微服务,提供生成订单服务
1.5.4.1 Dao层
package com.yf.shop.order.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.yf.shop.order.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
package com.yf.shop.order.mapper; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.yf.shop.order.pojo.Order; public interface OrderMapper extends baseMapper1.5.4.2 Service层{ }
package com.yf.shop.order.service;
import com.yf.common.Result;
import com.yf.common.order.params.OrderParams;
public interface OrderService {
public Result createOrder(OrderParams orderParams);
}
package com.yf.shop.order.service.impl;
import com.yf.common.Result;
import com.yf.shop.order.mapper.OrderMapper;
import com.yf.common.params.OrderParams;
import com.yf.shop.order.pojo.Order;
import com.yf.shop.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.RandomUtils;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Override
public Result createOrder(OrderParams orderParams) {
Order order = new Order();
order.setCreateTime(System.currentTimeMillis());
order.setGoodsId(orderParams.getGoodsId());
order.setUserId(orderParams.getUserId());
order.setOrderPrice(orderParams.getGoodsPrice());
order.setOrderId(System.currentTimeMillis()+""+orderParams.getUserId()+ ""+RandomUtils.nextInt(1000,9999));
order.setOrderStatus(0);
order.setPayStatus(0);
order.setPayTime(-1L);
this.orderMapper.insert(order);
return Result.success(order.getOrderId());
}
}
common模块
package com.yf.common.params;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class OrderParams {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String orderId;
private Long userId;
private Long goodsId;
private BigDecimal orderPrice;
private BigDecimal GoodsPrice;
}
1.5.4.3 Controller
package com.yf.shop.order.controller;
import com.yf.common.Result;
import com.yf.common.params.OrderParams;
import com.yf.shop.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("order")
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping("createOrder")
public Result createOrder(@RequestBody OrderParams orderParams){
return orderService.createOrder(orderParams);
}
}
1.5.5 下单业务
1.5.5.1 Controllercom.alibaba fastjson 1.2.76
package com.yf.shop.app.controller;
import com.yf.common.Result;
import com.yf.shop.app.model.params.BuyParams;
import com.yf.shop.app.service.BuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("buy")
public class BuyController {
@Autowired
private BuyService buyService;
@PostMapping("submit")
private Result submitOrder(@RequestBody BuyParams buyParams){
return buyService.submitOrder(buyParams);
}
}
package com.yf.shop.app.model.params;
import lombok.Data;
@Data
public class BuyParams {
private Long userId;
private Long goodsId;
}
1.5.5.2 Service
package com.yf.shop.app.service;
import com.yf.common.Result;
import com.yf.shop.app.model.params.BuyParams;
public interface BuyService {
Result submitOrder(BuyParams buyParams);
}
package com.yf.shop.app.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yf.common.Result;
import com.yf.common.goods.GoodsBO;
import com.yf.common.order.params.OrderParams;
import com.yf.common.user.UserBO;
import com.yf.shop.app.model.params.BuyParams;
import com.yf.shop.app.service.BuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.util.Map;
@Service
public class BuyServiceImpl implements BuyService {
@Autowired
private RestTemplate restTemplate;
@Override
public Result submitOrder(BuyParams buyParams) {
String userResult = restTemplate.getForObject("http://localhost:8001/user/findUser/" + buyParams.getUserId(), String.class);
Result userBOResult = JSON.parseObject(userResult,new TypeReference>(){});
if (userBOResult == null || !userBOResult.isSuccess() || userBOResult.getData() == null){
return Result.fail(10001,"用户不存在");
}
UserBO userBO = userBOResult.getData();
String goodsResult = restTemplate.getForObject("http://localhost:8002/goods/findGoods/" + buyParams.getGoodsId(), String.class);
Result goodsBOResult = JSON.parseObject(goodsResult,new TypeReference>(){});
if (goodsBOResult == null || !goodsBOResult.isSuccess() || goodsBOResult.getData() == null){
return Result.fail(10002,"商品不存在");
}
GoodsBO goodsBO = (GoodsBO) goodsBOResult.getData();
Integer goodsStock = goodsBO.getGoodsStock();
if (goodsStock < 0){
return Result.fail(10003,"商品库存不足");
}
BigDecimal goodsPrice = goodsBO.getGoodsPrice();
BigDecimal account = userBO.getAccount();
if (account.compareTo(goodsPrice) < 0){
return Result.fail(10004,"余额不足");
}
OrderParams orderParams = new OrderParams();
orderParams.setUserId(userBO.getId());
orderParams.setGoodsId(goodsBO.getId());
orderParams.setGoodsPrice(goodsBO.getGoodsPrice());
String orderResult = restTemplate.postForObject("http://localhost:8003/order/createOrder", orderParams, String.class);
Result orderResultString = JSON.parseObject(orderResult,new TypeReference>(){});
if (orderResultString == null || !orderResultString.isSuccess()){
return Result.fail(10005,"下单失败");
}
String orderId = orderResultString.getData();
return Result.success(orderId);
}
}
1.5.5.3 测试
{
"success": true,
"code": 200,
"msg": "success",
"data": "162384788039011376"
}
从上述的代码 可以看出,下单业务 调用各个微服务的时候 极其不方便。
一旦服务提供方 更改ip,端口,接口名称等,服务消费方 也需要跟着变
如果服务提供方有多台服务器呢?服务消费方还得需要维护这些ip信息,甚至自己实现负载均衡。
这时候 就需要 服务治理。
接下来还会写几篇博客来介绍什么是服务治理和Spring Cloud Alibaba Nacos介绍以及Nacos实战项目



