1. Establishment of micro-service environment
1. Prepare a template
1.1.1 Technology Selection (Alibaba)
SpringCloud Alibaba
Sentinel,GateWay,Sleuth,ZipKin,Nacos Config,Seata
1.1.2 Module design
Springcloud – alibaba, the parent project
- Temp-common public module
- Temp-order order microservice
- Temp-item Item micro service
- Temp-gateway Indicates the micro-service gateway
1.1.3 Deployment List
Application Service Name | IP | port | instructions |
---|---|---|---|
temp-gateway | localhost | 7000 | |
temp-order | localhost | 8081 | |
temp-item | localhost | 8181, 8182, | Test openfeign |
Install the server middleware list
The middleware | IP | port | instructions |
---|---|---|---|
Nacos Discovery (1.4.1) | localhost | 8848 | Service discovery |
Nacos Config (1.4.1) | localhost | 8848 | Service configuration |
sentinel dashbord | localhost | 8080 | Service fault tolerance (service degradation, service traffic limiting, service fuse) |
zipkin server+sleuth | localhost | 9411 | Service link tracing |
feign | HTTP client for load balancing | ||
seata | Distributed transaction | ||
mysql | localhost | 3306 | storage |
1.1.4 Microservice invocation
Simple requirement: Before saving the order, call the product microservice to check the product information, so as to verify the inventory and price.
Caller: temp-order
Supplier: temp-item
1.2 Environment Installation
1.2.1 installation nacos
Download: github.com/alibaba/nac…
Download the installation package in ZIP format and decompress the current version nacOS-server-1.4.1.zip
The decompression directory is./run_env
1.2.1.1 start nacos
Windows
# change directory
cd ./run_env/nacos/bin
# command start
nacos/bin> ./startup.cmd -m standalone
Copy the code
Note: If the port is occupied, go to nacos\conf\application.properties to change 8848 to another unused port
1.2.1.2 access nacos
Open the browser to http://localhost:8848/nacos, you can access the service, the default password is nacos/nacos
1.2.2 Installing the Sentinel Console
Sentinel provides a lightweight console that provides machine discovery, real-time monitoring of stand-alone resources, and rule management.
1.2.2.1 Download the JAR package and decompress it to the folder
Github.com/alibaba/Sen…
1.2.2.2 Starting the console
# directly using the jar command to start the project (the console itself is a SpringBoot project) Java - Dserver. Port = 8080 - Dcsp. Sentinel. Dashboard. Server = localhost: 8080 - Dproject. Name = sentinel dashboard - jar sentinel - dashboard - 1.8.0 comes with. The jar
Copy the code
1.2.2.3 Accessing the console
Address: http://localhost:8080/
The default user name and password are sentinel/sentinel
Hint: how the console works
Sentinel’s console is actually a program written by SpringBoot. We need to register the microserver with the console
On (that is, in the micro service to specify the console address, and also open a port to transfer data to the console, the console can also pass
Through this port, the monitoring program in the microservice is called to obtain various information about the microservice.
1.2.2.4 Adding the configuration for the console
Modify temp-order’s application.yml
spring:
cloud:
sentinel:
transport:
port: 9999 Port to communicate with the console
dashboard: localhost:8080 Specify the address of the console service
Copy the code
1.2.3 Installing the ZipKin server
1.2.3.1 Downloading the ZipKin JAR Package
Search.maven.org/remote_cont…
Visit the url above to get a zipkin-server-2.12.9-exec.jar
1.2.3.2 Starting the ZipKin Server on the CLI
Java jar zipkin - server - 2.12.9 - exec. JarCopy the code
1.2.3.3 Using a Browserhttp://localhost:9411access
1.2.4 Installing the Docker Mysql Database
docker-compose.yaml
version: '3'
services:
mysql_server:
container_name: mysql_temp
image: Mysql: 8.0.11
environment:
MYSQL_DATABASE: temp_db
MYSQL_USER: admin
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: rootpassword
expose:
- 3306
ports:
- 3306: 3306
volumes:
# startup script
- ./docker-compose/mysql/initdb:/docker-entrypoint-initdb.d/
# DB persistence
- ddd_mysql_db:/var/lib/mysql
volumes:
ddd_mysql_db:
driver: local
Copy the code
Docker-compose \mysql\initdb; And create temp_db. SQL
# CREATE DATABASE temp_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
USE temp_db;
SET CHARACTER_SET_CLIENT = utf8;
SET CHARACTER_SET_CONNECTION = utf8;
CREATE TABLE IF NOT EXISTS temp_item (
id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
name varchar(30) NOT NULL COMMENT 'Trade Name',
price decimal(9.2) NOT NULL COMMENT 'price',
stock_num int NOT NULL COMMENT 'inventory'.PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='goods';
INSERT INTO temp_item VALUE(NULL.'iphone6'.4000.50);
INSERT INTO temp_item VALUE(NULL.'iphone6s'.4500.50);
INSERT INTO temp_item VALUE(NULL.'iphone7'.5000.50);
INSERT INTO temp_item VALUE(NULL.'iphone7plus'.5500.50);
Copy the code
Install and execute docker mysql
docker-compose up -d
Copy the code
1.3 Creating a Parent Project
Create a Maven project and add the following to the POM.xml file
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>
<modules>
<module>temp-common</module>
<module>temp-item</module>
</modules>
<! -- Specify parent project -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2. RELEASE</version>
</parent>
<groupId>com.temp</groupId>
<artifactId>springcloud-alibaba</artifactId>
<version>1.0 the SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<! When choosing SpringCloud and Alibaba versions, be sure to follow the advice of the official website, otherwise there will be problems.
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.5. RELEASE</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<! -- Spring Cloud dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<! -- Spring Cloud Alibaba -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<! -- Nacos Discovery is a dependency that every microservice needs to use, so extract the parent class -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<! - fegin component - >
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<! -- Link Tracing Sleuth+ZipKin-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<! -- Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<! --nacos config-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
</project>
Copy the code
Version:
Github.com/alibaba/spr…
Spring Cloud Alibaba Version | Sentinel Version | Nacos Version | RocketMQ Version | Dubbo Version | Seata Version | Spring Cloud Version | Spring Boot Version |
---|---|---|---|---|---|---|---|
2.2.5. RELEASE | 1.8.0 comes with | 1.4.1 | 4.4.0 | 2.7.8 | 1.3.0 | Hoxton.SR8 | 2.3.2. RELEASE |
1.4 Creating the Common Module
Create the temp-common module
1.4.1 Adding dependencies to POM.xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-alibaba</artifactId>
<groupId>com.temp</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>temp-common</artifactId>
<dependencies>
<! -- Add persistence layer framework -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<properties>
<mysql.version>5.1.6</mysql.version>
<fastjson.version>1.2.56</fastjson.version>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
</project>
Copy the code
1.4.2 Creating entity Classes
Item.java
package com.temp.po;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name = "temp_item")
@Data
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;/ / the primary key
private String name;// Product name
private Double price;// Commodity prices
private Integer stockNum;/ / inventory
}
Copy the code
Order.java
package com.temp.po;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name = "temp_order")
@Data
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long oid;/ / order id
private Integer uid;/ / user id
private String uname;/ / user name
private Integer itemid;Id / / commodities
private String name;// Product name
private Double price;// Unit price
private Integer number;// Purchase quantity
}
Copy the code
1.5 Create commodity microservices
Create a module named temp-item
1.5.1 Adding a SpringBoot Dependency
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-alibaba</artifactId>
<groupId>com.temp</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>temp-item</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.temp</groupId>
<artifactId>temp-common</artifactId>
<version>1.0 the SNAPSHOT</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
</project>
Copy the code
1.5.2 Creating a Project main Class
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ItemApplication {
public static void main(String[] args) { SpringApplication.run(ItemApplication.class, args); }}Copy the code
1.5.3 Creating the Configuration file Application.yml
server:
port: 8181
spring:
application:
name: service-item
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: JDBC: mysql: / / 127.0.0.1:3306 / temp? useUnicode=true&characterEncoding=utf-8
username: root
password: root
jpa:
properties:
hibernate:
hbm2ddl:
auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Copy the code
1.5.4 Creating the ItemDao Interface
package com.temp.dao;
import com.temp.po.Item;
import org.springframework.data.jpa.repository.JpaRepository;
/** * JPA interface */
public interface ItemDao extends JpaRepository<Item.Integer> {}Copy the code
1.5.5 Creating the ItemService interface and implementation class
ItemService.java
package com.temp.service;
import com.temp.po.Item;
public interface ItemService {
Item queryItemById(Integer id);
}
Copy the code
ItemServiceImpl.java
package com.temp.service;
import com.temp.dao.ItemDao;
import com.temp.po.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private ItemDao dao;
@Override
public Item queryItemById(Integer id) {
returndao.findById(id).get(); }}Copy the code
1.5.6 create Controller
package com.temp.controller;
import com.temp.po.Item;
import com.temp.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("/item/{id}")
public Item query(@PathVariable Integer id) {
returnitemService.queryItemById(id); }}Copy the code
1.5.7 Start microservices and access apis
1.6 Creating an order microservice
1.6.1 Adding a SpringBoot Dependency
<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>springcloud-alibaba</artifactId>
<groupId>com.temp</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>temp-order</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.temp</groupId>
<artifactId>temp-common</artifactId>
<version>1.0 the SNAPSHOT</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
</project>
Copy the code
1.6.2 Creating the main class of the project
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) { SpringApplication.run(OrderApplication.class,args); }}Copy the code
1.6.3 Creating the Configuration file application.yml
server:
port: 8081
spring:
application:
name: service-order
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: JDBC: mysql: / / 127.0.0.1:3306 / temp_db? useUnicode=true&characterEncoding=utf-8
username: root
password: rootpassword
jpa:
properties:
hibernate:
hbm2ddl:
auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Copy the code
1.6.4 Creating the OrderDao Interface
package com.temp.dao;
import com.temp.po.Order;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderDao extends JpaRepository<Order.Long> {}Copy the code
1.6.5 Creating the OrderService interface and implementation class
OrderService.java
package com.temp.service;
import com.temp.po.Order;
public interface OrderService {
public void save(Order order);
}
Copy the code
OrderServiceImpl.java
package com.temp.service;
import com.temp.dao.OrderDao;
import com.temp.po.Order;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class OrderServiceImpl implements OrderService{
@Autowired
private OrderDao orderDao;
@Override
public void save(Order order) { orderDao.save(order); }}Copy the code
1.6.6 Add the RestTemplate to the original main Class
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
/** * The newly appended RestTemplate *@return RestTemplate
*/
@Bean
public RestTemplate getRestTemplate(a){
return newRestTemplate(); }}Copy the code
1.6.7 create Controller
package com.temp.controller;
import com.temp.po.Item;
import com.temp.po.Order;
import com.temp.service.OrderService;
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.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private OrderService orderService;
@GetMapping("/order/item/{id}")
public Order saveOrder(@PathVariable("id") Integer id){
Item item = restTemplate.getForObject(
"http://localhost:8181/item/"+id,Item.class);
Order order = new Order();
order.setUid(1);
order.setUname("Order package");
order.setItemid(item.getId());
order.setName(item.getName());
order.setPrice(item.getPrice());
order.setNumber(1);
orderService.save(order);
returnorder; }}Copy the code
1.6.8 Start the project and test by accessing the service through a browser
2. Service Governance (Nacos Discovery)
2.1 NACOS Registration Service
2.1.1 Register commodity microservices with NACOS
Further modify the temp-item module code and register it with the NACOS service
2.1.1.1 Add @enableDiscoveryClient to the main Class
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ItemApplication {
Copy the code
2.1.1.2 Add the NACOS address in application.yml
spring:
application:
name: service-item
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: JDBC: mysql: / / 127.0.0.1:3306 / temp_db? useUnicode=true&characterEncoding=utf-8
username: root
password: rootpassword
jpa:
properties:
hibernate:
hbm2ddl:
auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Service Governance -- NacOS registry services
cloud:
nacos:
discovery:
server-addr: 127.0. 01.: 8848
Copy the code
2.1.1.3 Go to the NACOS console to check whether the registration is successful
After the order micro-service registration, unified view
2.1.2 Register the order microservice with NACOS
2.1.2.1 Annotate @enableDiscoveryClient and Fegin on the main class
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients / / open Feigin
public class OrderApplication {
Copy the code
2.1.2.2 Add the NACOS service address in application.yml
server:
port: 8081
spring:
application:
name: service-order
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: JDBC: mysql: / / 127.0.0.1:3306 / temp_db? useUnicode=true&characterEncoding=utf-8
username: root
password: rootpassword
jpa:
properties:
hibernate:
hbm2ddl:
auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Service Governance -- NacOS registry services
cloud:
nacos:
discovery:
server-addr: 127.0. 01.: 8848
Copy the code
2.1.2.3 Create a Service and implement the microservice invocation using Feigin
ItemService.java
package com.temp.service;
import com.temp.po.Item;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient("service-item")// Declare the provider name of the call
public interface ItemService {
Item queryItemById(@PathVariable("id") Integer id);
}
Copy the code
2.1.2.4 Modify the Controller code and start the verification
@Autowired
private RestTemplate restTemplate;
@Autowired
private OrderService orderService;
@Autowired
private ItemService itemService;
@GetMapping("/order/item/{id}")
public Order saveOrder(@PathVariable("id") Integer id){
// Item item = restTemplate.getForObject(
// "http://localhost:8181/item/"+id,Item.class);
// OpenFeign based remote call, default integrated Robbin load balancing
Item item = itemService.queryItemById(id);
Order order = new Order();
order.setUid(1);
order.setUname("Order package");
order.setItemid(item.getId());
order.setName(item.getName());
order.setPrice(item.getPrice());
order.setNumber(1);
orderService.save(order);
return order;
}
Copy the code
2.1.2.5 Restart the Order microservice to check the effect
3. Service fault-tolerant Sentinel
3.1 Micro service integration Sentinel
Microservice integration with Sentinel is very simple, just adding the Sentinel dependencies
package com.temp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SentinelController {
@RequestMapping("/sentinel/test")
public String test(a){
return "OK";
}
@RequestMapping("/sentinel/test2")
public String test2(a){
return "OK-test2"; }}Copy the code
3.2 Feign integration with Sentinel
3.2.1 Enable Feign’s support for Sentinel in the configuration file
Service Governance -- NacOS registry services
cloud:
nacos:
discovery:
server-addr: 127.0. 01.: 8848
# Enable Feign support for Sentinel
feign:
sentinel:
enabled: true
Copy the code
3.2.2 Specify fault-tolerant classes for fault-tolerant interfaces
import com.temp.po.Item;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
//@FeignClient("service-item")=>@FeignClient(value = "service-item")
@FeignClient(value = "service-item")// Declare the provider name of the invocation =>value used to specify which microservice under NACOS to invoke
public interface ItemService {
@GetMapping(value="/item/{id}")// Specify the URI part of the request
Item queryItemById(@PathVariable("id") Integer id);
}
Copy the code
3.2.3 modify Controller
@RestController
@Slf4j
public class OrderController {
// @Autowired
// private RestTemplate restTemplate;
@Autowired
private OrderService orderService;
@Autowired
private ItemService itemService;
@GetMapping("/order/item/{id}")
public Order saveOrder(@PathVariable("id") Integer id){
// Item item = restTemplate.getForObject(
// "http://localhost:8181/item/"+id,Item.class);
/ / left left left left left left left left left left down down down down down down down down down left left left left left left left left left left down down down down down down down down down left left left left left left left left left left left down down down down down down down down down left left left left left left left left left left left left left down down down down down down down down down
// OpenFeign based remote call, default integrated Robbin load balancing
Item item = itemService.queryItemById(id);
Order order = new Order();
order.setUid(1);
order.setUname("Order package");
order.setItemid(item.getId());
order.setName(item.getName());
order.setPrice(item.getPrice());
order.setNumber(1);
// Comment temporarily to prevent frequent order creation
// orderService.save(order);
returnorder; }}Copy the code
3.2.4 Stop all temp-item services, restart the temp-order service, access requests, and observe the fault tolerance effect
4. Service Gateway Gateway
4.1 Quick Start
4.1.1 Create a temp-gateway module and import related dependencies
pom.xml
<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>springcloud-alibaba</artifactId>
<groupId>com.temp</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>temp-gateway</artifactId>
<properties>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<dependencies>
<! --gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
</project>
Copy the code
4.1.2 Creating a Main Class
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args){ SpringApplication.run(GatewayApplication.class,args); }}Copy the code
4.1.3 Adding a Configuration File
server:
port: 7000
spring:
application:
name: temp-gateway
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848
file-extension: yml
shared-dataids: temp-common-config.yml
refreshable-dataids: temp-common-config.yml
gateway:
discovery:
locator:
enabled: true Allow gateways to detect microservices in NACOS
routes:
- id: temp_route
uri: lb://service-order # LB is getting microservices from NACOS by name and following a load balancing policy.
predicates:
- Path=/order-serv/**
filters:
- StripPrefix=1
Copy the code
4.1.4 Start the project and access the micro-service through the gateway
Check the nacos
Then access the service-order and service-item services through gateway 7000
4.2 integrated Nacos
Currently, the address of the forwarding path is written dead in the configuration file, which causes many problems. Next, we get this address from the registry.
4.2.1 Adding nacOS Dependencies
<! -- nacos client-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code
4.2.2 Add annotations to the main class
package com.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args){ SpringApplication.run(GatewayApplication.class,args); }}Copy the code
4.2.3 Modifying a Configuration File
server:
port: 7000
spring:
application:
name: temp-gateway
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848
# file-extension: properties
# shared-dataids: temp-gateway.properties
# refreshable-dataids: temp-gateway.properties
gateway:
discovery:
locator:
enabled: true Allow gateways to detect microservices in NACOS
routes:
- id: item_route
uri: lb://service-item # LB is getting microservices from NACOS by name and following a load balancing policy.
predicates:
- Path=/item-serv/**
filters:
- StripPrefix=1
Copy the code
4.2.4 test
4.3 Gateway Traffic Limiting
4.3.1 Importing Dependencies
<! --Gateway current limit-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
Copy the code
4.3.2 Writing configuration classes
The Gateway based on Sentinel current limit is accomplished by providing a Filter, when using only need to inject the corresponding SentinelGatewayFilter instances and SentinelGatewayBlockExceptionHandler instance.
public class GatewayConfiguration {
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public GatewayConfiguration(ObjectProvider
> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer)
{
this.viewResolvers =
viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
/** * Initialize a current-limiting filter */
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter(a){
return new SentinelGatewayFilter();
}
/** * Configure initial current limiting parameters */
@PostConstruct
public void initGatewayRules(a){
Set<GatewayFlowRule> rules = new HashSet<>();
rules.add(
new GatewayFlowRule("item_route")// Resource name, corresponding to route id
.setCount(1) // Current limit threshold
.setIntervalSec(1) // Statistical time window, the unit is second, the default is 1 second
);
GatewayRuleManager.loadRules(rules);
}
/**
* Configure current limiting exception handler
* @return SentinelGatewayBlockExceptionHandler
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler(a){
return new SentinelGatewayBlockExceptionHandler(
viewResolvers,
serverCodecConfigurer
);
}
/** * Custom current limit exception page */
@PostConstruct
public void initBlockHandlers(a){
BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
Map map = new HashMap<>();
map.put("code".0);
map.put("message"."The interface is current limited");
returnServerResponse .status(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(map)); }}; GatewayCallbackManager.setBlockHandler(blockRequestHandler); }}Copy the code
4.3.3 test
A second visit http://localhost:7000/item-serv/item/1 for many times, whether current limit.
normal
Frequent request
You can see the restrictor working.
5. Service link tracing Sleuth+ZipKin
5.1 introduction to Sleuth
Add dependencies, see parent project
5.2 Zipkin client integration
The integration of the Zipkin client and Sleuth is as simple as adding its dependencies and configurations in the microservice.
5.2.1 Add dependencies on each microservice
Add dependencies, see parent project
5.2.2 Adding a Configuration
spring:
application:
name: temp-gateway
zipkin:
base-url: http://127.0.0.1:9411/ #zipkin server of request address
discovery-client-enabled: false # Let nacos treat it as a URL, not as a service name
sleuth:
sampler:
probability: 1.0 #Sampled percentage
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848
Copy the code
5.2.3 Accessing microservices
In the gateway, for example
5.2.4 Visit Zipkin’s UI interface and observe the effect
6. Service configuration Nacos Config
6.1 Nacos Config Getting started
6.1.1 Setting up the NACOS Environment
Use the existing NACOS environment
6.1.2 Introduce nacOS dependency
Add dependencies, see parent project
6.1.3 Adding the Nacos Config Configuration
Note: Instead of using the original application.yml configuration file, create a new bootstrap.yml configuration file
Configuration file priority (from highest to lowest)
bootstrap.properties -> bootstrap.yml -> application.properties -> application.yml
temp-item/src/resources/bootstrap.yml
spring:
application:
name: service-item
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848 # nacos center address
file-extension: yaml # Configuration file format
Copy the code
6.1.4 Adding the Configuration in NACOS
The temp – directly to the item/SRC/resources/application. The yml configuration content, the following issue
Note: It is a good idea to restart microservices whenever configuration changes
6.1.5 Start the program for testing
service-order
service-item
service-gateway
If yes, nacos Config is successfully configured
6.2 Nacos Config Advanced
6.2.1 Sharing Configurations of Different Micro-services (service-item, service-order)
The principle of configuration sharing between different microservices is similar to file import, that is, defining a common configuration and importing it into the current configuration.
- In nacOS, a DataID is defined as temp-common-service.yaml configuration for all microservice shares
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: JDBC: mysql: / / 127.0.0.1:3306 / temp_db? useUnicode=true&characterEncoding=utf-8
username: root
password: rootpassword
jpa:
properties:
hibernate:
hbm2ddl:
auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
cloud:
nacos:
discovery:
server-addr: 127.0. 01.: 8848
sentinel:
transport:
dashboard: 127.0. 01.: 8888
zipkin:
base-url: http://127.0.0.1:9411/
discovery-client-enabled: false
sleuth:
sampler:
probability: 1.0
Copy the code
2. Modify the bootstrap yaml
server:
port: 8181
spring:
application:
name: service-item
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848 # nacos center address
file-extension: yaml # Configuration file format
shared-dataids: temp-common-service.yaml
refreshable-dataids: temp-common-service.yaml
sentinel:
transport:
port: 8722
Copy the code
3 Start the microservice for testing
7. Distributed transaction Seata
7.1 installation Seata
7.1.1 download Seata
Github.com/seata/seata…
7.1.2 Modifying a Configuration File
Decompress and go to the conf directory and modify the following files:
registry.conf
Registry {type = "nacos" nacOS {application = "seata-server" serverAddr = "127.0.0.1:8848" group = "SEATA_GROUP" namespace = "public" cluster = "default" username = "nacos" password = "nacos" } } config { type = "nacos" nacos { ServerAddr = "127.0.0.1:8848" Namespace = "public" group = "SEATA_GROUP" username = "nacos" password = "nacos" # dataId = "seataServer.properties" } }Copy the code
Config.txt (originally not available, need to be created in seata-server-1.4.2)
Note: the initialization scripts used to store the various configuration centers are read from the config.txt configuration file and written to the configuration center.)
service.vgroup_mapping.service-item=default
service.vgroup_mapping.service-order=default
Copy the code
7.1.3 Starting NACOS Initialize the seATA configuration
On Windows, use Git Bash Here to do this
Download it here: github.com/seata/seata… On the seata server — 1.4.2 \ conf
Enter on the Git bash screen
Sh -h 127.0.0.1 -p 8848 -g SEATA_GROUP -t public -u nacos -w nacOS $sh nacos-config.sh -h 127.0.0.1 -p 8848 -g SEATA_GROUP -t public -u nacos -w nacossetNacosAddr = 127.0.0.1:8848set group=SEATA_GROUP
Set service.vgroup_mapping.service-item=default successfully
Set service.vgroup_mapping.service-order=default successfully
=========================================================================
Complete initialization parameters, total-count:2 , failure-count:0
=========================================================================
Init nacos config finished, please start seata-server.
Copy the code
7.14 Starting the Seata Service
cd bin
seata-server.bat -p 8900 -m file
Copy the code