当前位置:网站首页>03_ Case setup [resttemplate calls microservices]
03_ Case setup [resttemplate calls microservices]
2022-07-18 13:35:00 【Book opens autumn maple】
1. Business Introduction
Distributed system using microservice architecture , Microservices communicate with each other over the network . We describe the calling relationship between microservices through service providers and service consumers .
Service providers : The callee of the service , The party that provides the calling interface
Serving consumers : The caller of the service , The party that relies on other services
We take e-commerce system as an example , The user initiates a purchase request to the order microservice . Before saving the order You need to call the commodity micro service to query the current commodity inventory , Unit price and other information . In this case , Order micro service is a service consumption person , Commodity micro service is a service provider .

2. Set up the environment
2.1 stay IDEA Create parent project in shop_parent And introduce coordinates
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.10.RELEASE</version>
<relativePath/>
</parent>
<packaging>pom</packaging>
<properties>
<java.version>1.8</java.version>
<spring.cloud-version>Hoxton.SR8</spring.cloud-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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.suke.springcloud</groupId>
<artifactId>002-shop-service-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<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>2.2 Create a microservice engineering module
Create common modules shop_service_common: Used to store public entity classes and tool classes
Create order micro service module shop_service_order
Create a commodity micro service module shop_service_product
Create user micro service module shop_service_user
2.3 Set the dependency structure of the dependent project, such as

3. Build a commodity micro service
3.1 Write entity class
stay shop_service_common Created in com.suke.model.Product Entity class , And configuration .
public class Product implements Serializable {
private Long id;
private String productName;
private Integer status;
private Double price;
public Product() {
}
public Product(Long id) {
this.id = id;
}
public Product(Long id, String productName) {
this.id = id;
this.productName = productName;
}
}3.2 To write service layer
stay shop_service_product in establish com.suke.service.ProductService
public interface ProductService {
// according to id Inquire about
Product findById(Long id);
// Query all
List findAll();
}stay shop_service_product Created in com.suke.service.ProductServiceImpl Implementation class
@Service
public class ProductServiceImpl implements ProductService {
@Override
public Product findById(Long id) {
return new Product(id,"apple");
}
@Override
public List findAll() {
return null;
}
}3.3 To write web layer
stay shop_service_product Created in com.suke.controller.ProductController
controller Used in @GetMapping It's a composite annotation , amount to @RequestMapping(method="get")
There are similar notes @PostMapping,@PutMapping,@DeleteMapping
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/{id}")
public Product findById(@PathVariable Long id) {
System.out.println("--------003---------");
return productService.findById(id);
}
@GetMapping("/{id}/{name}")
public Product findById(@PathVariable Long id, @PathVariable String name) {
return new Product(id, name);
}
@GetMapping
public List findAll() {
return productService.findAll();
}
}3.4 Configure startup class
stay shop_service_product Created in com.suke.ProductApplication Start class
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// To configure RestTemplate hand spring management
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}3.5 To configure yml file
server:
port: 9004
servlet:
context-path: /004-shop-service-order
eureka:
client:
service-url:
defaultZone: http://localhost:9005/005-shop-eureka-server/eureka/,http://localhost:9006/006-shop-eureka-server/eureka/
instance:
prefer-ip-address: true # Use ip register
lease-expiration-duration-in-seconds: 10 #eureka client Send a heartbeat to server After end , Renewal time ( Default 90 second )
lease-renewal-interval-in-seconds: 3 # Send heartbeat renewal interval
# instance-id: ${spring.cloud.client.ip-address}:${server.port}
spring:
application:
name: 004-shop-service-order4. Other micro Services
Time is limited and the configuration logic is similar , User microservices and order microservices are the same .
5. The service call
We have written three basic microservices , When users place an order, they need to call the commodity micro service to get the commodity data . So how do you do that ? Commodity microservices provide invoked HTTP Interface . So it can be used when placing an order http The requested tool class is completed , As is common HttpClient,OkHttp, You can also use it Spring Provided RestTemplate.
5.1 RestTemplate Introduce
Spring Framework provided RestTemplate Class can be invoked in application. rest service , It simplifies and http The way services communicate , system throughout RESTful Standards for , Encapsulates the http link , We just need to pass in url And return value type . Compared with the previous commonly used HttpClient,RestTemplate Is a more elegant call RESTful Way of service .
stay Spring Access to third parties in the application REST Service and use Spring RestTemplate Class about .RestTemplate Class design Principles and many others Spring Template class ( for example JdbcTemplate、JmsTemplate) identical , It provides a tool for performing complex tasks Simplified method with default behavior .
RestTemplate Default dependency JDK Provide http The ability to connect (HttpURLConnection), If necessary, you can also go through setRequestFactory Method is replaced by, for example Apache HttpComponents、Netty or OkHttp Others, such as HTTP library.
in consideration of RestTemplate Class is called for REST Designed for service , So its main method is to REST It is not enough that the foundation of is closely connected It's amazing , The latter is HTTP Protocol approach :HEAD、GET、POST、PUT、DELETE and OPTIONS. for example , RestTemplate Class has headForHeaders()、getForObject()、postForObject()、put() and delete() Other methods .
5.2 RestTemplate Methods to introduce

5.3 adopt RestTemplate Call microservices
(1) stay shop_service_order In Engineering OrderApplication Start class Middle configuration RestTemplate
// To configure RestTemplate hand spring management
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}(2) Write order placement method
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
RestTemplate restTemplate;
@GetMapping("/{id}")
public Product order(@PathVariable(name = "id") Long id) {
System.out.println("id:" + id);
Product product = restTemplate.getForObject("http://localhost:9003/003-shop-service-product/product/789", Product.class);
Product product = restTemplate.getForObject("http://localhost:9003/003-shop-service-product/product/{1}", Product.class,123);
Map map = new HashMap();
map.put("id", 258);
map.put("name", "watermelon");
Product product = restTemplate.getForObject("http://localhost:9003/003-shop-service-product/product/{id}", Product.class,map);
Product product = restTemplate.getForObject("http://localhost:9003/003-shop-service-product/product/{id}/{name}", Product.class, map);
ResponseEntity<Product> entity = restTemplate.getForEntity("http://localhost:9003/003-shop-service-product/product/789", Product.class);
System.out.println(entity.getStatusCode());
System.out.println(entity.getStatusCodeValue());
System.out.println(entity.getBody());
return product;
}
}5.4 Problems with hard coding
So far, we have been able to pass RestTemplate Call commodity micro service RESTFul API Interface . But we put the provider's network address (ip, port ) When it's hard coded into the code , There are many problems with this approach :
Application scenarios are limited and cannot be dynamically adjusted, so how to solve it , You need to dynamically register and discover services through the registry .
边栏推荐
- Task-Customized Self-Supervised Pre-training with Scalable Dynamic Routing
- Template_ Real dichotomy
- Sword finger offer 28 Symmetric binary tree
- Task-Customized Self-Supervised Pre-training with Scalable Dynamic Routing
- gan网络学习笔记
- The third day of MATLAB learning (data types, operators and various operations)
- Time consuming evaluation of image pixel values accessed by opencv, emgucv and opencvsharp pointers (with source code)
- Language AI originally knew whether his answer was correct! New research in Berkeley and other universities is hot, netizen: dangerous, dangerous, dangerous
- [machine learning] random forest
- constrained graphic layout generation via latent optimization
猜你喜欢

探索式軟件測試

Detailed explanation of some functions with similar functions in MySQL

Expert routine of BW conversion based on AMDP
![[software testing] test slang, the advice given to you by ten-year old employees](/img/69/b27255c303150430df467ff3b5cd08.gif)
[software testing] test slang, the advice given to you by ten-year old employees

语言AI原来知道自己的回答是否正确!伯克利等高校新研究火了,网友:危险危险危险...
![[notes] cryptography from introduction to earth | des](/img/a1/5c6d32e3e4fc15afbf6d7d86644c54.png)
[notes] cryptography from introduction to earth | des

EXCEL,选择数据如何选择合适的图表?

DLS-42/4-4 DC110V双位置继电器

【软件测试】08 -- 黑盒测试方法(边界值分析法、因果图与决策表法)

gan网络学习笔记
随机推荐
快速上手Jupyter Notebook
Working people working soul! Here comes the sales analysis case!
DzzOffice_ Flowplayer player changes
Find the number of daffodils
Sword finger offer 63 Maximum profit of stock
DPR-34、AC220V双位置继电器
Common protocols of tcp/ip
Gan online learning notes
[RT thread] NXP rt10xx sfud and fal component construction and use
Community summit pulsar summit old golden peak conference topic highlights exposure!
5、 Basic composition & assertion of JMeter script
内网部署EDUSOHO遇到的问题
猜数字大小II[动态规划解决什么问题?]
Jishili multimeter dmm6500
[machine learning] PCA - principal component analysis
How to restore the files deleted from the U disk
Sword finger offer 47 Maximum value of gifts
Research progress of transfer learning in medical image classification
Sword finger offer 10- I. Fibonacci sequence
[software testing] 08 -- black box testing method (boundary value analysis method, cause and effect diagram and decision table method)