Spring cloud pure dry goods, from introduction to actual combat

Chen Yanbin 2020-11-10 00:28:18
spring cloud pure dry goods


Reading guide

I wrote one before SpringCloud From beginners to proficient Point me direct. , Micro service Basics Point me direct. , Today we use Spring Cloud Simulate an e-commerce project . They are as follows 2 A service , goods 、 Order . Now let's start

Technology stack

  1. SpringBoot Integrate SpringCloud
  2. communication mode :http restful
  3. Registry Center :eruka
  4. Circuit breaker :hystrix
  5. gateway :zuul

Goods and services

The function point

  • List of goods
  • Goods details

Order service

The function point

  • My order
  • Order interface

build Eureka Server

Create project

Project structure

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 https://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.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>eureka_server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka_server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Annotate the startup class

application.properties

# Service port number
server.port=8761
# eureka Host name
eureka.instance.hostname=localhost
# Specifies whether the current host needs to register with the registry ( no need , Because the current host is Server, No Client)
eureka.client.register-with-eureka=false
# Specifies whether the current host needs to obtain registration information ( no need , Because the current host is Server, No Client)
eureka.client.fetch-registry=false
# Address of Registration Center
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

Start the service and check the monitor station

build Eureka Client Goods and services

Create project

Project structure

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 https://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.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>product_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>product_service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
View Code

application.properties

# Service port number
server.port=8771
# The service name
spring.application.name=product_service
# Register the service with the registry ,eureka_service The address of
eureka.client.service-url.defaultZone:http://localhost:8761/eureka/

ProductController.java

package com.ybchen.product_service.controller;
import com.ybchen.product_service.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName:ProductController
* @Description: goods
* @Author:chenyb
* @Date:2020/11/1 8:42 Afternoon
* @Versiion:1.0
*/
@RestController
@RequestMapping("/api/v1/product")
public class ProductController {
@Autowired
private ProductService productService;
/**
* List of goods
*
* @return
*/
@PostMapping("list")
public Object list() {
return productService.listProduct();
}
/**
* according to id Query products
*
* @param id
* @return
*/
@GetMapping("findById")
public Object findById(@RequestParam("id") int id) {
return productService.findById(id);
}
}

Product.java

package com.ybchen.product_service.domain;
import java.io.Serializable;
/**
* @ClassName:Product
* @Description: Commodity entity class
* @Author:chenyb
* @Date:2020/11/1 8:43 Afternoon
* @Versiion:1.0
*/
public class Product implements Serializable {
/**
* Internal code
*/
private String id;
/**
* Name of commodity
*/
private String name;
/**
* Price , Divided into units
*/
private int price;
/**
* stock
*/
private int store;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getStore() {
return store;
}
public void setStore(int store) {
this.store = store;
}
public Product() {
}
public Product(String id, String name, int price, int store) {
this.id = id;
this.name = name;
this.price = price;
this.store = store;
}
@Override
public String toString() {
return "product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", price=" + price +
", store=" + store +
'}';
}
}
View Code

ProductService.java

package com.ybchen.product_service.service;
import com.ybchen.product_service.domain.Product;
import java.util.List;
/**
* @ClassName:ProductService
* @Description: goods service
* @Author:chenyb
* @Date:2020/11/1 8:45 Afternoon
* @Versiion:1.0
*/
public interface ProductService {
/**
* List of goods
* @return
*/
List<Product> listProduct();
/**
* according to id Query products
* @param id
* @return
*/
Product findById(int id);
}

ProductServiceImpl.java

package com.ybchen.product_service.service.impl;
import com.ybchen.product_service.domain.Product;
import com.ybchen.product_service.service.ProductService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @ClassName:ProductServiceImpl
* @Description:ProductService Implementation class
* @Author:chenyb
* @Date:2020/11/1 8:47 Afternoon
* @Versiion:1.0
*/
@Service
public class ProductServiceImpl implements ProductService {
// Initialize memory commodity data . Simulate the goods stored in the database 
private static final Map<Integer, Product> daoMap = new HashMap<>();
@Value("${server.port}")
private String port;
static {
for (int i = 0; i < 5; i++) {
daoMap.put(i, new Product(i + "", "iphone_" + i, 1000 * i, 10));
}
}
@Override
public List<Product> listProduct() {
Collection<Product> values = daoMap.values();
return new ArrayList<>(values);
}
@Override
public Product findById(int id) {
Product product = daoMap.get(id);
product.setName(product.getName()+"_"+port);
return product;
}
}

ProductServiceApplication.java

package com.ybchen.product_service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}

Start up and check the monitor station

start-up 2 A service , And check the monitor station

build Eureka Client Order service

Create project

Project structure

 

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 https://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.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>order_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>order_service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

application.properties

# Service port number
server.port=8781
# The service name
spring.application.name=order-service
# Register the service with the registry ,eureka_service The address of
eureka.client.service-url.defaultZone:http://localhost:8761/eureka/

OrderServiceApplication.java

Startup class add Ribbon annotation

 @Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
package com.ybchen.order_service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class OrderServiceApplication {
/**
* Load balancing Ribbon
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}

OrderController.java

package com.ybchen.order_service.controller;
import com.ybchen.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("api/v1/order")
public class OrderController {
@Autowired
private ProductOrderService productOrderService;
@RequestMapping("save")
public Object save(@RequestParam("user_id")int userId,@RequestParam("product_id")int productId){
return productOrderService.save(userId,productId);
}
}

ProductOrder.java

package com.ybchen.order_service.domain;
import java.util.Date;
/**
* Commodity order entity class
*/
public class ProductOrder {
/**
* Primary key
*/
private int id;
/**
* Name of commodity
*/
private String productName;
/**
* Order serial number
*/
private String tradeNo;
/**
* Price , In quantile units
*/
private int price;
/**
* Creation time
*/
private Date createTime;
/**
* user id
*/
private String userId;
/**
* User name
*/
private String userName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getTradeNo() {
return tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "ProductOrder{" +
"id=" + id +
", productName='" + productName + '\'' +
", tradeNo='" + tradeNo + '\'' +
", price=" + price +
", createTime=" + createTime +
", userId='" + userId + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
View Code

ProductOrderService.java

package com.ybchen.order_service.service;
import com.ybchen.order_service.domain.ProductOrder;
public interface ProductOrderService {
ProductOrder save(int userId, int productId);
}

ProductOrderServiceImpl.java

package com.ybchen.order_service.service.impl;
import com.ybchen.order_service.domain.ProductOrder;
import com.ybchen.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @ClassName:ProductOrderServiceImpl
* @Description: Product order implementation class
* @Author:chenyb
* @Date:2020/11/2 11:34 Afternoon
* @Versiion:1.0
*/
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private RestTemplate restTemplate;
/**
* Order interface
* @param userId user id
* @param productId product id
* @return
*/
@Override
public ProductOrder save(int userId, int productId) {
Object obj=productId;
//get The way 
Object forObject = restTemplate.getForObject("http://product-service/api/v1/product/findById?id=" + productId, Object.class);
//post The way
// Map<String,String> map=new HashMap<>();
// map.put("id","1");
// String s = restTemplate.postForObject("http://product-service/api/v1/product/test", map, String.class);
// System.out.println(s);
 System.out.println(forObject);
// Get product details 
ProductOrder productOrder=new ProductOrder();
productOrder.setTradeNo(UUID.randomUUID().toString());
productOrder.setCreateTime(new Date());
productOrder.setUserId(userId+"");
return productOrder;
}
}

Test load balancing

feign actual combat

brief introduction

Transform order service , Call commodity service to get product information

Website example

Point me direct.

Transform order service

add to feign rely on

 <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<?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 https://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.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>order_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>order_service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--openfeign rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Add comments to the startup class

Add on startup class :@EnableFeignClients

 

Add an interface

 

ProductClient.java

package com.ybchen.order_service.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Commodity Services client
*/
// name= Service name of commodity service ==========》spring.application.name=product-service
@FeignClient(name = "product-service")
@RequestMapping("/api/v1/product")
public interface ProductClient {
@GetMapping("findById")
String findById(@RequestParam("id") int id);
}

modify ProductOrderServiceImpl.java

The original

package com.ybchen.order_service.service.impl;
import com.ybchen.order_service.domain.ProductOrder;
import com.ybchen.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @ClassName:ProductOrderServiceImpl
* @Description: Product order implementation class
* @Author:chenyb
* @Date:2020/11/2 11:34 Afternoon
* @Versiion:1.0
*/
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private RestTemplate restTemplate;
/**
* Order interface
* @param userId user id
* @param productId product id
* @return
*/
@Override
public ProductOrder save(int userId, int productId) {
Object obj=productId;
//get The way 
Object forObject = restTemplate.getForObject("http://product-service/api/v1/product/findById?id=" + productId, Object.class);
//post The way
// Map<String,String> map=new HashMap<>();
// map.put("id","1");
// String s = restTemplate.postForObject("http://product-service/api/v1/product/test", map, String.class);
// System.out.println(s);
 System.out.println(forObject);
// Get product details 
ProductOrder productOrder=new ProductOrder();
productOrder.setTradeNo(UUID.randomUUID().toString());
productOrder.setCreateTime(new Date());
productOrder.setUserId(userId+"");
return productOrder;
}
}

It is amended as follows

 

package com.ybchen.order_service.service.impl;
import com.ybchen.order_service.domain.ProductOrder;
import com.ybchen.order_service.service.ProductClient;
import com.ybchen.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.UUID;
/**
* @ClassName:ProductOrderServiceImpl
* @Description: Product order implementation class
* @Author:chenyb
* @Date:2020/11/2 11:34 Afternoon
* @Versiion:1.0
*/
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private ProductClient productClient;
/**
* Order interface
*
* @param userId user id
* @param productId product id
* @return
*/
@Override
public ProductOrder save(int userId, int productId) {
//----------- Call the commodity service to start ------------
String byId = productClient.findById(productId);
System.out.println(byId);
//----------- Call commodity service end ------------
// Get product details 
ProductOrder productOrder = new ProductOrder();
productOrder.setTradeNo(UUID.randomUUID().toString());
productOrder.setCreateTime(new Date());
productOrder.setUserId(userId + "");
return productOrder;
}
}

Testing goods and services

Add ( Set the service call timeout )

Default connection 10 second , Read 60 second , But because of hystrix The default is 1 Second timeout

Official website case , Point me direct.

application.properties

# Set connection and read timeout
feign.client.config.default.connect-timeout=5000
feign.client.config.default.read-timeout=1100

Service degradation and fusing (Hystrix)

Why use ?

In a distributed system , A service depends on multiple services , There may be a service call failure , For example, timeout. 、 Abnormal etc. , How to ensure that in the case of a dependency problem , It will not lead to overall service failure , Can pass Hystrix To solve .

Website example

Point me direct.

Modify order service

Add dependency

 <!--hystrix rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<?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 https://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.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>order_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>order_service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--openfeign rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--hystrix rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
View Code

Start class annotate

@EnableCircuitBreaker

Modify the control layer

adding annotations ,@HystrixCommand, and Define callback methods , Return value 、 The input parameters must be consistent !!!!

Enter the reference 、 Return value , Inconsistency will result in an error

feign combination Hystrix

Modify order service

Turn on hystrix

 

# Turn on hystrix
feign.hystrix.enabled=true

ProductClient.java

 

package com.ybchen.order_service.service;
import com.ybchen.order_service.fallback.ProductClientFallBack;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/**
* Commodity Services client
*/
// name= Service name of commodity service ==========》spring.application.name=product-service
@FeignClient(name = "product-service",fallback = ProductClientFallBack.class)
//@RequestMapping("/api/v1/product")
public interface ProductClient {
@GetMapping("/api/v1/product/findById")
String findById(@RequestParam("id") int id);
}

ProductClientFallBack.java

 

package com.ybchen.order_service.fallback;
import com.ybchen.order_service.service.ProductClient;
import org.springframework.stereotype.Component;
/**
* For goods and services , Do demotion
*/
@Component
public class ProductClientFallBack implements ProductClient {
@Override
public String findById(int id) {
System.out.println(" Goods and services have been downgraded ~~~~~~~");
return null;
}
}

Verify that goods and services are fused

Why is the product service fused , And it's back to this result , That's because service Implementation class , Something went wrong inside

 

Alarm notification of fuse degradation service ( important )

Let's write some pseudo code , such as :xxx Microservices are down , And then by text message 、 The way the mail is , Notify the appropriate Developer , Emergency treatment of accidents, etc .

Modify order service

modify hystrix Timeout time

Disable timeout ( Not recommended )

hystrix.command.default.execution.timeout.enabled=false

Set timeout ( recommend )

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=4000

Source location explanation

In this way , You can also set more hystrix The default value is

Circuit breaker Dashboard Monitoring instrument cluster

Modify order service

Add dependency

 <!--hystrix The dashboard -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<?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 https://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.18.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>order_service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>order_service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--openfeign rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--hystrix rely on -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--hystrix The dashboard -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
pom.xml

Annotate the startup class

add to :@EnableHystrixDashboard

 

Modify the configuration file

# Expose all monitoring information
management.endpoints.web.exposure.include=*

Access the dashboard

http://127.0.0.1:8781/hystrix
http://127.0.0.1:8781/actuator/hystrix.stream

The dashboard is not very useful in actual work ( Different people have different opinions ), It's just for learning , Specific parameters , Please Baidu , Just blow up the microservice / Degraded alarm notification is handled well , Better than anything

Microservice gateway Zuul

Create project

Project structure

 

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 https://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.2.11.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ybchen</groupId>
<artifactId>api-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
pom.xml

application.properties

server.port=8800
# The service name
spring.application.name=api-gateway
# Register the service with the registry ,eureka_service The address of
eureka.client.service-url.defaultZone:http://localhost:8761/eureka/

Default access rules

http://gateway:port/service-id/**

such as , Original order address :127.0.0.1:8781/api/v1/order/save?user_id=1&product_id=1

Now order address :127.0.0.1:8800/order-service/api/v1/order/save?user_id=1&product_id=1

Custom routing rules

add to application.properties Information

 

# Custom routing rules , grammar :zuul.routes. service name = Custom routing
zuul.routes.order-service=/apigate/**
# Don't let the default service expose the interface , grammar :zuul.ignored-patterns= service name
zuul.ignored-patterns=/order-service/**
# Ignore all services
# zuul.ignored-patterns=*

Handle http The request header is empty

  Default zuul Filter 3 It's worth ("Cookie", "Set-Cookie", "Authorization"), Solve the version , Set to not filter

Source code interpretation

Add attribute

# Handle http The request header is empty
zuul.sensitive-headers=

Customize Zuul Filter login authentication

reform api-gateway project

newly build LoginFilter class

Create a new class , And inheritance ZuulFilter, Rewrite the methods inside

 

package com.ybchen.apigateway.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
/**
* @ClassName:LoginFilter
* @Description: Login filter
* @Author:chenyb
* @Date:2020/11/8 11:16 Afternoon
* @Versiion:1.0
*/
@Component // Give Way Spring Scan to 
public class LoginFilter extends ZuulFilter {
/**
* Filter type , There are the following types
* 1、pre
* 2、route
* 3、post
* 4、error
*
* @return
*/
@Override
public String filterType() {
return PRE_TYPE;
}
/**
* Filter sequence , The smaller, the better
*
* @return
*/
@Override
public int filterOrder() {
return 4;
}
/**
* Whether the filter works or not
*
* @return
*/
@Override
public boolean shouldFilter() {
//1、 Get context 
RequestContext currentContext = RequestContext.getCurrentContext();
//2、 obtain HttpServletRequest
HttpServletRequest request = currentContext.getRequest();
//3、 Get the request path , Determine whether to intercept
//System.out.println(request.getRequestURL()); //http://127.0.0.1:8800/apigate/order/api/v1/order/save
//System.out.println(request.getRequestURI()); ///apigate/order/api/v1/order/save
String url = request.getRequestURI();
System.out.println(" Request path url=========>" + url);
if ((url == null ? "" : url.toLowerCase()).startsWith("/apigate/order")) {
return true;
}
return false;
}
/**
* Filter logic , Business logic
*
* @return
* @throws ZuulException
*/
@Override
public Object run() throws ZuulException {
System.out.println(" Request blocked ==============");
//JWT The way
//1、 Get context 
RequestContext currentContext = RequestContext.getCurrentContext();
//2、 obtain HttpServletRequest
HttpServletRequest request = currentContext.getRequest();
//3、 Get token
String token = request.getHeader("token"); // Ask the head to take token
if (token == null || "".equals(token)) {
token = request.getParameter("token"); //get The way to get token
 }
// Login verification logic , It's recommended here JWT The way , Do login authentication 
if (token == null || "".equals(token)) {
//4、 Don't let it go down 
currentContext.setSendZuulResponse(false);
//5、 Set status code ,401,Unauthorized
 currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
sendJsonMessage(currentContext.getResponse()," The user is not logged in ");
}
return null;
}
/**
* Respond to json Data to front end
*
* @param response
* @param obj
*/
private void sendJsonMessage(HttpServletResponse response, Object obj) {
try {
ObjectMapper objectMapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(objectMapper.writeValueAsString(obj));
writer.close();
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}

User login authentication test

Add

Login authentication , Recommended JWT The way , Now I'm going to offer you a previous project ,JWT Tool class of , And part of the key code of the interceptor

 <dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
pom.xml rely on
package net.ybclass.online_ybclass.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.ybclass.online_ybclass.model.entity.User;
import java.util.Date;
/**
* JWT Tool class
* Be careful :
* 1、 Generated token, It can be done by base64 To decipher the inscriptions
* 2、base64 To decrypt the plaintext information , Modify and code , The decryption will fail
* 3、 It is not possible to void the promulgated token, Unless you change the key
*/
public class JWTUtils {
/**
* Expiration time , a week
*/
static final long EXPIRE = 60000 * 60 * 24 * 7;
/**
* Encryption key
*/
private static final String SECRET = "ybclass.net168";
/**
* Token prefix
*/
private static final String TOKEN_PREFIX = "ybclass";
/**
* The theme
*/
private static final String SUBJECT = "ybclass";
/**
* According to user information , To generate the token
*
* @param user
* @return
*/
public static String geneJsonWebToken(User user) {
String token = Jwts.builder().setSubject(SUBJECT)
.claim("head_img", user.getHeadImg())
.claim("id", user.getId())
.claim("name", user.getName())
.setIssuedAt(new Date()) // Token issue time 
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) // Expiration time 
.signWith(SignatureAlgorithm.HS256, SECRET) // encryption 
 .compact();
token = TOKEN_PREFIX + token;
return token;
}
/**
* check token Method
*
* @param token
* @return
*/
public static Claims checkJWT(String token) {
try {
final Claims claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
return claims;
} catch (Exception e) {
return null;
}
}
}
JWTUtils.java
try {
String accesToken = request.getHeader("token");
if (accesToken == null) {
accesToken = request.getParameter("token");
}
if (StringUtils.isNoneBlank(accesToken)) {
Claims claims = JWTUtils.checkJWT(accesToken);
if (claims == null) {
sendJsonMessage(response, JsonData.buildError(" Login expired , Please login again "));
// Tell the login to expire , Log in again
return false;
}
Integer id = (Integer) claims.get("id");
String name = (String) claims.get("name");
request.setAttribute("user_id", id);
request.setAttribute("name", name);
return true;
}
} catch (Exception e) {
}
// Login failed
sendJsonMessage(response, JsonData.buildError(" Login expired , Please login again "));
return false;
=================
User user = userMapper.findByPhoneAndPwd(phone, CommonUtils.MD5(pwd));
return user == null ? null : JWTUtils.geneJsonWebToken(user);
Interceptor part of the code

gateway Zuul Interface current limiting

Using Google guava frame , Gateway current limiting

reform api-gateway project

establish OrderRatelimiterFilter

And then inherit ZuulFilter, And use springcloud inherited guava technology , Only for order interface current limit !!!

 

package com.ybchen.apigateway.filter;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
/**
* @ClassName:OrderRateLimiterFilter
* @Description: Order interface current limit
* @Author:chenyb
* @Date:2020/11/9 11:32 Afternoon
* @Versiion:1.0
*/
public class OrderRateLimiterFilter extends ZuulFilter {
// Current limiting token , How many tokens are created per second , Be careful :springcloud Default Integration guava
private static final RateLimiter RATE_LIMITER = RateLimiter.create(1000);
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return -4;
}
@Override
public boolean shouldFilter() {
//1、 Get context 
RequestContext currentContext = RequestContext.getCurrentContext();
//2、 obtain HttpServletRequest
HttpServletRequest request = currentContext.getRequest();
String url = request.getRequestURI();
System.out.println(" Current limiting request path url=========>" + url);
// Only the order interface is limited 
if ((url == null ? "" : url.toLowerCase()).startsWith("/apigate/order")) {
return true;
}
return false;
}
@Override
public Object run() throws ZuulException {
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
if (!RATE_LIMITER.tryAcquire()) {
currentContext.setSendZuulResponse(false);
currentContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
}
return null;
}
}

Zuul colony

Technology stack :nginx+lvs+keepalive

Case source code download

 link : https://pan.baidu.com/s/1bNIh-8nSCMcU7FjVVzlBnA password : 4wf9

 

版权声明
本文为[Chen Yanbin]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云