Spring Cloud Alibaba
致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用微服务的必需组件,方便开发者通过Spring Cloud
编程模型轻松使用这些组件来开发分布式应用服务。
依托Spring Cloud Alibaba
,只需要添加一些注解和少量配置,就可以将Spring Cloud
应用接入阿里微服务解决方案,通过阿里中间件来迅速搭建分布式应用系统。
我们本次是使用的电商项目中的商品、订单、用户为案例进行讲解。
在微服务架构中,最常见的场景就是微服务之间的相互调用。我们以电商系统中常见的用户下单为例来演示微服务的调用:客户向订单微服务发起一个下单的请求,在进行保存订单之前需要调用商品微服务查询商品的信息。
我们一般把服务的主动调用方称为服务消费者,把服务的被调用方称为服务提供者。
在这种场景下,订单微服务就是一个服务消费者,商品微服务就是一个服务提供者。
创建一个maven工程,然后在pom.xml
文件中添加下面内容
<?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 http://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.3.RELEASE</version>
</parent>
<groupId>it.aq.cheetah</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
<spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
版本对应:
在pom.xml
中添加依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.aq.cheetah</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>shop-common</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
</dependencies>
</project>
//用户信息
@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
模块,然后进行下面操作
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.aq.cheetah</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>shop-user</artifactId>
<dependencies>
<dependency>
<groupId>it.aq.cheetah</groupId>
<artifactId>shop-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
@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 依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.aq.cheetah</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>shop-product</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>it.aq.cheetah</groupId>
<artifactId>shop-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
@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<ShopProduct> {}
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 依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.aq.cheetah</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>shop-order</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>it.aq.cheetah</groupId>
<artifactId>shop-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
@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<OrderMapper, ShopOrder> implements IOrderService {}
@Mapper
public interface OrderMapper extends BaseMapper<ShopOrder> {}
@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后端知识,请点击文末名片与我交流吧。留下您的一键三连,让我们在这个寒冷的东西互相温暖吧!