从浅入深 学习 SpringCloud 微服务架构(二)模拟微服务环境(2)通过 RestTemplate 调用远程服务
段子手168
1、打开 idea 创建父工程
创建 artifactId 名为 spring_cloud_demo 的 maven 工程。
--> idea --> File
--> New --> Project
--> Maven Project SDK: ( 1.8(java version "1.8.0_131" )
--> Next
--> Groupld : ( djh.it )Artifactld : ( spring_cloud_demo )Version : 1.0-SNAPSHOT
--> Name: ( spring_cloud_demo )Location: ( C:\java-test\idea2019\spring_cloud_demo\ )
--> Finish
2、在父工程 spring_cloud_demo 的 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><groupId>djh.it</groupId><artifactId>spring_cloud_demo</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version><scope>provided</scope></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Greenwich.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>http://repo.spring.io/libs-snapshot-local</url><snapshots><enabled>true</enabled></snapshots></repository><repository><id>spring-milestones</id><name>Spring Milestones</name><url>http://repo.spring.io/libs-milestone-local</url><snapshots><enabled>false</enabled></snapshots></repository><repository><id>spring-releases</id><name>Spring Releases</name><url>http://repo.spring.io/libs-release-local</url><snapshots><enabled>false</enabled></snapshots></repository></repositories><pluginRepositories><pluginRepository><id>spring-snapshots</id><name>Spring Snapshots</name><url>http://repo.spring.io/libs-snapshot-local</url><snapshots><enabled>true</enabled></snapshots></pluginRepository><pluginRepository><id>spring-milestones</id><name>Spring Milestones</name><url>http://repo.spring.io/libs-milestone-local</url><snapshots><enabled>false</enabled></snapshots></pluginRepository></pluginRepositories><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project><!-- C:\java-test\idea2019\spring_cloud_demo\pom.xml -->
3、在父工程 spring_cloud_demo 下,创建子工程(子模块)
创建 子工程(子模块)
--> 右键 spring_cloud_demo 父工程
--> Modules
--> Maven
--> Groupld : ( djh.it )Artifactld : ( order_service )Version : 1.0-SNAPSHOT
--> Next
--> Module name: ( order_service )Content root : ( C:\java-test\idea2019\spring_cloud_demo\order_service )Module file location: ( C:\java-test\idea2019\spring_cloud_demo\order_service )
--> Finish
4、在子工程 order_service 的 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"><parent><artifactId>spring_cloud_demo</artifactId><groupId>djh.it</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>order_service</artifactId><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><!-- <version>5.1.32</version>--><version>8.0.26</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency></dependencies></project>
<!-- C:\java-test\idea2019\spring_cloud_demo\order_service\pom.xml -->
5、准备数据库表
— 创建数据库:
create database shop;
— 使用数据库:
use shop;
— 创建数据表:
CREATE TABLE `tb_product` (`id` int NOT NULL AUTO_INCREMENT,`product_name` varchar(40) DEFAULT NULL COMMENT '名称',`status` int DEFAULT NULL COMMENT '状态',`price` decimal(10,2) DEFAULT NULL COMMENT '单价',`product_desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '描述',`caption` varchar(255) DEFAULT NULL COMMENT '标题',`inventory` int DEFAULT NULL COMMENT '库存',PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3
— 插入数据:
insert into `tb_product` (`id`, `product_name`, `status`, `price`, `product_desc`, `caption`, `inventory`) values('1','iPhone 15 Pro','1','7999.00','iPhone 15 Pro 6.7 英寸或 6.1 英寸, 超视网膜 XDR 显示屏,ProMotion 自适应刷新率技术,钛金属搭配亚光质感玻璃背板, 灵动岛功能, A17 Pro 芯片,配备 6 核图形处理器, Pro 级摄像头系统,主摄 4800 万像素 | 超广角 | 长焦, 10 倍, 支持 USB 3, 视频播放最长可达 29 小时。 ','iPhone 15 Pro 巅峰之作','99');
6、创建配置文件 application.yml
## C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\resources\application.ymlserver:port: 9002 # 启动端口 命令行注入。
# port: ${port:9002} # 启动端口设置为动态传参,如果未传参数,默认端口为 9002
# servlet:
# context-path: /application1spring:application:name: service-order #spring应用名, # 注意 FeignClient 不支持名字带下划线
# main:
# allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。datasource:driver-class-name: com.mysql.jdbc.Driver # mysql 驱动
# url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: 12311jpa:database: MySQLshow-sql: trueopen-in-view: true
7、创建 商品实体类 Product.java
/*** C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\java\djh\it\order\domain\Product.java** 2024-4-19 商品实体类 Product.java*/
package djh.it.order.domain;import lombok.Data;
import java.math.BigDecimal;@Data
public class Product {private Long id;private String productName;private Integer status;private BigDecimal price;private String productDesc;private String caption;private Integer inventory;
}
8、创建 订单的 controller 类 OrderController.java
/*** C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\java\djh\it\order\controller\OrderController.java** 2024-4-19 订单的 controller 类 OrderController.java*/
package djh.it.order.controller;import djh.it.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;@RestController
@RequestMapping("/order")
public class OrderController {// 注入 restTemplate 对象@Autowiredprivate RestTemplate restTemplate;/*** 参数:商品的 id* 通过订单系统,调用商品服务根据id查询商品信息。* 1)需要配置商品对象。* 2)需要调用商品服务。* 可以使用 java 中的 urlconnection, HttpClient, OkHttp 进行远程调用。* 也可以使用 restTemplate 进行远程调用。** @param id* @return*/@RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)public Product findById(@PathVariable Long id){Product product = null;/*** 调用商品服务(将微服务的请求路径硬编码到 java 代码中)* 存在问题:对微服务调用的负载均衡,加入API网关,配置的统一管理,链路追踪。*/product = restTemplate.getForObject("http://127.0.0.1:9001/product/1", Product.class);return product;}
}
9、创建 订单 启动类 OrderApplication.java
/*** C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\java\djh\it\order\OrderApplication.java** 2024-4-19 启动类 OrderApplication.java*/
package djh.it.order;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
@EntityScan("djh.it.order.domain")
public class OrderApplication {/*** 使用 spring 提供的 RestTemplate 发送 http 请求到商品服务。* 1)创建 RestTemplate 对象交给容器管理。* 2)在使用的时候,调用其方法完成操作(getXX, postXX)。 **/@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(OrderApplication.class, args);}
}
10、运行启动类,进行测试
浏览器地址栏输入:http://127.0.0.1:9002/order/buy/1
输出 mysql 数据库的第一条记录:
上一节文章查看请点击
从浅入深 学习 SpringCloud 微服务架构(二)模拟微服务环境(1)