欢迎来到阿Q社区
https://bbs.csdn.net/topics/617897123
Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用微服务的必需组件,方便开发者通过Spring Cloud编程模型轻松使用这些组件来开发分布式应用服务。
依托Spring Cloud Alibaba ,只需要添加一些注解和少量配置,就可以将Spring Cloud应用接入阿里微服务解决方案,通过阿里中间件来迅速搭建分布式应用系统。
我们本次是使用的电商项目中的商品、订单、用户为案例进行讲解。

在微服务架构中,最常见的场景就是微服务之间的相互调用。我们以电商系统中常见的用户下单为例来演示微服务的调用:客户向订单微服务发起一个下单的请求,在进行保存订单之前需要调用商品微服务查询商品的信息。
我们一般把服务的主动调用方称为服务消费者,把服务的被调用方称为服务提供者。

在这种场景下,订单微服务就是一个服务消费者,商品微服务就是一个服务提供者。
创建一个maven工程,然后在pom.xml文件中添加下面内容
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.3.RELEASE it.aq.cheetah microservice 1.0-SNAPSHOT pom 1.8 8 8 UTF-8 UTF-8 Greenwich.RELEASE 2.1.0.RELEASE org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import
版本对应:

在pom.xml中添加依赖
4.0.0 it.aq.cheetah microservice 1.0-SNAPSHOT shop-common 8 8 UTF-8 com.baomidou mybatis-plus-boot-starter 3.5.0 org.projectlombok lombok 1.18.26 com.alibaba fastjson 1.2.83 mysql mysql-connector-java 8.0.31
//用户信息
@Data
@TableName(value = "shop_user")
public class ShopUser {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;//主键
@TableField("username")
private String username;//用户名
@TableField("password")
private String password;//密码
@TableField("telephone")
private String telephone;//手机号
}
//商品信息
@Data
@TableName(value = "shop_product")
public class ShopProduct {
@TableId(value = "id",type = IdType.AUTO)
private Long id;//主键
@TableField("pname")
private String pname;//商品名称
@TableField("pprice")
private Double pprice;//商品价格
@TableField("stock")
private Integer stock;//库存
}
//订单信息
@Data
@TableName(value = "shop_order")
public class ShopOrder {
@TableId(value = "id",type = IdType.AUTO)
private Long id;//订单id
@TableField("uid")
private Long uid;//用户id
@TableField("username")
private String username;//用户名
@TableField("pid")
private Long pid;//商品id
@TableField("pname")
private String pname;//商品名称
}
新建一个shop-user模块,然后进行下面操作
4.0.0 it.aq.cheetah microservice 1.0-SNAPSHOT shop-user it.aq.cheetah shop-common 1.0-SNAPSHOT
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
server:
port: 8071
#数据库配置
spring:
application:
name: shop-user
datasource:
url: jdbc:mysql://127.0.0.1:3306/microservice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
#模板引擎配置
thymeleaf:
encoding: UTF-8
#suffix: .html 默认后缀
#prefix: classpath:/templates/ 默认前缀
mybatis-plus:
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapper-locations: classpath:mapper/*Mapper.xml
# 加载全局的配置文件
config-location: classpath:mybatis-config.xml
# 搜索指定包别名
typeAliasesPackage: it.aq.cheetah.**.entity
添加 springboot 依赖
4.0.0 it.aq.cheetah microservice 1.0-SNAPSHOT shop-product org.springframework.boot spring-boot-starter-web it.aq.cheetah shop-common 1.0-SNAPSHOT
@SpringBootApplication
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class,args);
}
}
server:
port: 8081
#数据库配置
spring:
application:
name: shop-product
datasource:
url: jdbc:mysql://127.0.0.1:3306/microservice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
#模板引擎配置
thymeleaf:
encoding: UTF-8
#suffix: .html 默认后缀
#prefix: classpath:/templates/ 默认前缀
mybatis-plus:
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapper-locations: classpath:mapper/*Mapper.xml
# 加载全局的配置文件
config-location: classpath:mybatis-config.xml
# 搜索指定包别名
typeAliasesPackage: it.aq.cheetah.**.entity
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
@Autowired
private IProductservice productService;
/**
* @Description:查询商品信息
* @Author: cheetah
* @Date: 2024/1/22 9:40
* @param id:
* @return: it.aq.cheetah.entity.ShopProduct
**/
@GetMapping("/{id}")
public ShopProduct product(@PathVariable("id") Long id) {
ShopProduct product = productService.findByPid(id);
log.info("查询到商品:" + JSON.toJSONString(product));
return product;
}
/**
* @Description:扣减库存
* @Author: cheetah
* @Date: 2024/1/22 9:40
* @param productReduceDTO:
* @return: it.aq.cheetah.entity.ShopProduct
**/
@PostMapping("/reduceStock")
public Integer reduceStock(@RequestBody ProductReduceDTO productReduceDTO) {
return productService.reduceStock(productReduceDTO);
}
}
@Service
public class ProductServiceImpl implements IProductservice {
@Autowired
private ProductMapper productMapper;
@Override
public ShopProduct findByPid(Long pid) {
return productMapper.selectById(pid);
}
@Override
public Integer reduceStock(ProductReduceDTO productReduceDTO) {
ShopProduct shopProduct = productMapper.selectById(productReduceDTO.getProductId());
Integer stock = shopProduct.getStock();
if(stock < productReduceDTO.getReductCount()){
throw new RuntimeException("库存不足,请联系管理员增加库存");
}
shopProduct.setStock(stock-productReduceDTO.getReductCount());
return productMapper.updateById(shopProduct);
}
}
@Mapper
public interface ProductMapper extends BaseMapper {}
INSERT INTO shop_product VALUE(NULL,'小米','1000','5000'); INSERT INTO shop_product VALUE(NULL,'华为','2000','5000'); INSERT INTO shop_product VALUE(NULL,'苹果','3000','5000'); INSERT INTO shop_product VALUE(NULL,'OPPO','4000','5000');

添加 springboot 依赖
4.0.0 it.aq.cheetah microservice 1.0-SNAPSHOT shop-order org.springframework.boot spring-boot-starter-web it.aq.cheetah shop-common 1.0-SNAPSHOT
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
}
server:
port: 8091
#数据库配置
spring:
application:
name: shop-order
datasource:
url: jdbc:mysql://127.0.0.1:3306/microservice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
#模板引擎配置
thymeleaf:
encoding: UTF-8
#suffix: .html 默认后缀
#prefix: classpath:/templates/ 默认前缀
mybatis-plus:
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapper-locations: classpath:mapper/*Mapper.xml
# 加载全局的配置文件
config-location: classpath:mybatis-config.xml
# 搜索指定包别名
typeAliasesPackage: it.aq.cheetah.**.entity
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
@Autowired
private IOrderService orderService;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{pid}")
public ShopOrder order(@PathVariable("pid") Long pid) {
log.info("客户下单,这时候要调用商品微服务查询商品信息。。。");
ShopProduct shopProduct = restTemplate.getForObject("http://127.0.0.1:8081/product/" + pid, ShopProduct.class);
log.info("当前用户信息为自己,假设我们设置为1");
ShopOrder shopOrder = new ShopOrder();
shopOrder.setUid(1L);
shopOrder.setUsername("公众号:阿Q说代码");
shopOrder.setPid(shopProduct.getId());
shopOrder.setPname(shopProduct.getPname());
orderService.save(shopOrder);
//商品扣减库存的逻辑
ProductReduceDTO productReduceDTO = new ProductReduceDTO();
productReduceDTO.setProductId(pid);
productReduceDTO.setReductCount(1);
Integer count = restTemplate.postForObject("http://127.0.0.1:8081/product/reduceStock", productReduceDTO, Integer.class);
return shopOrder;
}
}
@Service
public class OrderServiceImpl extends ServiceImpl implements IOrderService {}
@Mapper
public interface OrderMapper extends BaseMapper {}
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
同时启动商品服务和订单服务,执行http://127.0.0.1:8091/order/1完成后,查看数据库数据


到这儿,我们的微服务搭建基本完成了。接下来的文章,我们将继续完善我们的微服务系统,集成更多的Alibaba组件。让我们期待下一篇的文章吧!想要了解更多JAVA后端知识,请点击文末名片与我交流吧。留下您的一键三连,让我们在这个寒冷的东西互相温暖吧!
上一篇:SD-WAN企业组网场景深度解析