idea packages executable jar packages with maven

Posted by DrDankWD on Fri, 24 Dec 2021 09:12:33 +0100

***idea package executable jar package
Add the following in pom

 ~~<build>
        <plugins>~~Strikethrough format~~ 
            <plugin>
                <groupId>org.springframework.~~ boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.5.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Welcome to the Markdown editor

Hello! This is the welcome page displayed by the Markdown editor for the first time. If you want to learn how to use the Markdown editor, you can read this article carefully to understand the basic grammar of Markdown.

New changes

We have expanded some functions and syntax support for the Markdown editor. In addition to the standard Markdown editor functions, we have added the following new functions to help you blog with it:

  1. The new interface design will bring a new writing experience;
  2. Set your favorite code highlight style in the creation center, and Markdown will display the selected highlight style of code slice display;
  3. The picture drag function is added. You can drag local pictures directly to the editing area for direct display;
  4. New KaTeX mathematical formula syntax;
  5. Added mermaid syntax supporting Gantt chart 1 Function;
  6. The function of multi screen editing Markdown article is added;
  7. Functions such as focus writing mode, preview mode, concise writing mode and synchronous wheel setting in left and right areas are added. The function button is located between the editing area and preview area;
  8. Added check list function.

Function shortcut

Undo: Ctrl/Command + Z
Redo: Ctrl/Command + Y
Bold: Ctrl/Command + B
Italic: Ctrl/Command + I
Title: Ctrl/Command + Shift + H
Unordered list: Ctrl/Command + Shift + U
Ordered list: Ctrl/Command + Shift + O
Checklist: Ctrl/Command + Shift + C
Insert code: Ctrl/Command + Shift + K
Insert link: Ctrl/Command + Shift + L
Insert picture: Ctrl/Command + Shift + G
Find: Ctrl/Command + F
Replace: Ctrl/Command + G

Creating a reasonable title is helpful to the generation of the directory

Directly input once #, and press space to generate level 1 title.
After entering twice #, and pressing space, a level 2 title will be generated.
By analogy, we support level 6 titles. It helps to generate a perfect directory after using TOC syntax.

How to change the style of text

Emphasize text emphasize text

Bold text bold text

Tag text

Delete text

Reference text

H2O is a liquid.

210 the result is 1024

Insert links and pictures

Link: link.

Picture:

Pictures with dimensions:

Centered picture:

Centered and sized picture:

Of course, in order to make users more convenient, we have added the image drag function.

How to insert a beautiful piece of code

go Blog settings Page, select a code slice highlighting style you like, and the same highlighted code slice is shown below

// An highlighted block
var foo = 'bar';

Generate a list that suits you

  • project
    • project
      • project
  1. Item 1
  2. Item 2
  3. Item 3
  • Planning tasks
  • Complete the task

Create a table

A simple table is created as follows:

projectValue
computer$1600
mobile phone$12
catheter$1

The setting content is centered, left and right

Use: ---------: Center
Use: --------- left
Usage -----------: right

First columnSecond columnThird column
First column text centeredThe text in the second column is on the rightThe text in the third column is left

SmartyPants

SmartyPants converts ASCII punctuation characters to "smart" printed punctuation HTML entities. For example:

TYPEASCIIHTML
Single backticks'Isn't this fun?''Isn't this fun?'
Quotes"Isn't this fun?""Isn't this fun?"
Dashes-- is en-dash, --- is em-dash– is en-dash, — is em-dash

Create a custom list

Markdown Text-to- HTML conversion tool Authors John Luke

How to create a footnote

A text with footnotes. 2

Annotations are also essential

Markdown converts text to HTML.

KaTeX mathematical formula

You can render LaTeX mathematical expressions using KaTeX:

Gamma formula display Γ ( n ) = ( n − 1 ) ! ∀ n ∈ N \Gamma(n) = (n-1)!\quad\forall n\in\mathbb N Γ (n)=(n−1)! ∀ N ∈ N is through Euler integral

Γ ( z ) = ∫ 0 ∞ t z − 1 e − t d t   . \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. Γ(z)=∫0∞​tz−1e−tdt.

You can find more information about LaTeX mathematical expressions here.

New Gantt chart features to enrich your articles

Spring Cloud day 2

  1. Feign declarative service invocation

1.1 Feign overview

  1. Feign is a declarative REST client. It uses interface based annotation to facilitate client configuration
  2. Feign was initially provided by Netflix, but does not support spring MVC annotations. Later, it was encapsulated by spring cloud and supports spring MVC annotations, making it easier for users to accept.

1.2 Feign quick start

establish feign-parent:

<?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>org.example</groupId>
    <artifactId>feign-parent</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--spring boot environment -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--spring cloud edition-->
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <!--introduce Spring Cloud rely on-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>
</project>

Create Eureka server:

<?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>feign-parent</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eureka-server</artifactId>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- eureka-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

Eureka server startup class:

package com.itheima.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
// Enable EurekaServer
@EnableEurekaServer
public class EurekaApp {

    public static void main(String[] args) {
        SpringApplication.run(EurekaApp.class,args);

    }
}

Profile of Eureka server:

server:
  port: 8761


eureka:
  instance:
    hostname: localhost # host name
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka # eureka server address. The client will use this address to communicate with eureka in the future
    register-with-eureka: false # Whether to register your path to eureka. Not required by eureka server, but required by eureka provider client
    fetch-registry: false # Whether to grab the path from eureka. Not required by eureka server, but required by eureka consumer client
  server:
    enable-self-preservation: false # Turn off self-protection mechanism
    eviction-interval-timer-in-ms: 3000 # Check service interval

Create feign provider:

<?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>feign-parent</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>feign-provider</artifactId>

    <dependencies>

        <!--spring boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <!-- eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

    </dependencies>
</project>

Feign provider configuration file application yml:

server:
  port: 8001

eureka:
  instance:
    hostname: localhost # host name
    prefer-ip-address: true # Register the ip of the current instance with eureka server. The default is false to register the host name
    ip-address: 127.0.0.1 # Set the ip address of the current instance
    instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port} # Set the instance id displayed on the web console
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: feign-provider # Sets the name of the current app. It will be displayed in eureka Application in the future. You will need to use this name to get the path in the future

Startup class:

package com.itheima.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * Startup class
 */

@EnableEurekaClient //This annotation can be omitted in the new version
@SpringBootApplication
public class ProviderApp {


    public static void main(String[] args) {
        SpringApplication.run(ProviderApp.class,args);
    }
}

Controller:

package com.itheima.provider.controller;

import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Goods Controller service provider 
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;

    @GetMapping("/findOne/{id}")
    public Goods findOne(@PathVariable("id") int id){

        Goods goods = goodsService.findOne(id);

        goods.setTitle(goods.getTitle() + ":" + port);//Set the port number to the product title
        return goods;
    }
}

Service:

package com.itheima.provider.service;

import com.itheima.provider.dao.GoodsDao;
import com.itheima.provider.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Goods Business layer
 */
@Service
public class GoodsService {

    @Autowired
    private GoodsDao goodsDao;


    /**
     * Query by id
     * @param id
     * @return
     */
    public Goods findOne(int id){
        return goodsDao.findOne(id);
    }
}

Dao:

package com.itheima.provider.dao;

import com.itheima.provider.domain.Goods;
import org.springframework.stereotype.Repository;

import javax.validation.ReportAsSingleViolation;

/**
 * Commodity Dao
 */

@Repository
public class GoodsDao {


    public Goods findOne(int id){
        return new Goods(1,"Huawei mobile phone",3999,10000);
    }
}

pojo class:

package com.itheima.provider.domain;

/**
 * Commodity entity class
 */
public class Goods {

    private int id;
    private String title;//Product title
    private double price;//commodity price
    private int count;//Commodity inventory

    public Goods() {
    }

    public Goods(int id, String title, double price, int count) {
        this.id = id;
        this.title = title;
        this.price = price;
        this.count = count;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

Create feign consumer:

<?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>feign-parent</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>feign-consumer</artifactId>

    <dependencies>

        <!--spring boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <!-- eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!--feign-->
        <!--<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>-->

    </dependencies>
</project>

Feign consumer configuration file application yml:

server:
  port: 9000
eureka:
  instance:
    hostname: localhost # host name
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: feign-consumer # Sets the name of the current app. It will be displayed in eureka Application in the future. You will need to use this name to get the path in the future

Startup class:

package com.itheima.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableDiscoveryClient // Activate DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {


    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
}

Controller:

package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){

        String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
        // 3. Call method
        Goods goods = restTemplate.getForObject(url, Goods.class);


        return goods;
    }


}

Load balancing is added to the configuration of RestTemplate:

package com.itheima.consumer.config;


import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {


    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  1. Introduce open feign dependency on the consumer side


    org.springframework.cloud
    spring-cloud-starter-openfeign

  2. Write Feign call interface
    package com.itheima.consumer.feign;

    import com.itheima.consumer.domain.Goods;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    /**
     *
     * feign Declarative interface. The that initiated the remote call.
     *
     String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
     Goods goods = restTemplate.getForObject(url, Goods.class);
     *
     * 1. Define interface
     * 2. Add the annotation @ FeignClient on the interface and set the value attribute to the application name of the service provider
     * 3. Write the calling interface, and the declaration rules of the interface shall be consistent with the provider interface.
     * 4. Inject the interface object and call the interface method to complete the remote call
     *
     */
    
    @FeignClient(value = "FEIGN-PROVIDER")
    public interface GoodsFeignClient {
    
    
        @GetMapping("/goods/findOne/{id}")
        public Goods findGoodsById(@PathVariable("id") int id);
    
    }
    
  3. Add the @ EnableFeignClients annotation in the startup class to enable the Feign function
    package com.itheima.consumer;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    
    @EnableDiscoveryClient // Activate DiscoveryClient
    @EnableEurekaClient
    @SpringBootApplication
    @EnableFeignClients
    public class ConsumerApp {
    
    
        public static void main(String[] args) {
            SpringApplication.run(ConsumerApp.class,args);
        }
    }
    
    package com.itheima.consumer.controller;
    
    
    import com.itheima.consumer.domain.Goods;
    import com.itheima.consumer.feign.GoodsFeignClient;
    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.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    @RestController
    @RequestMapping("/order")
    public class OrderController {
    
        @Autowired
        private RestTemplate restTemplate;
    
        @Autowired
        private GoodsFeignClient goodsFeignClient;
        
        
        @GetMapping("/goods/{id}")
        public Goods findGoodsById(@PathVariable("id") int id){
    
    //        String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
    //        // 3.  Call method
    //        Goods goods = restTemplate.getForObject(url, Goods.class);
    
    
            return goodsFeignClient.findGoodsById(id);
        }
    
    
    }
    
  4. Test call

1.3 Feign other functions

1.3.1 Feign other functions - timeout setting

  1. Feign bottom layer relies on Ribbon to realize load balancing and remote call

  2. Ribbon defaults to 1 second timeout.

  3. Timeout configuration:

    ribbon:
    ConnectTimeout: 1000 # connection timeout, MS
    ReadTimeout: 1000 # logical processing timeout, MS

1.3.2 Feign other functions - logging

  1. Feign can only record debug level log information.
    logging:
    level:
    com.itheima: debug

  2. Define Feign log level Bean
    @Bean
    Logger.Level feignLoggerLevel() {
    return Logger.Level.FULL;
    }

  3. Enable this Bean:
    @FeignClient(configuration = XxxConfig.class)

  4. Hystrix fuse

2.1 overview of hystrix

  1. Hystix is an open-source delay and fault-tolerant Library of Netflix, which is used to isolate access to remote services and third-party libraries to prevent cascading failures (avalanches).
  2. Avalanche: a service failure that causes the service of the whole link to fail.

Main functions of Hystix

• isolation

• downgrade

• fusing

• current limiting

2.1. 1 Isolation

  1. Isolation:
    1. Thread pool isolation

    2. Semaphore isolation

2.1. 2. Degradation: abnormal, timeout

2.1. 3 fuse

2.1. 4 current limiting

2.2 hytrix downgrade

  1. Hystix degradation: returns the default data when the service has an exception or the call times out

2.2.1 Hystrix downgrade – service provider

  1. In the service provider, introduce the hystrix dependency


    org.springframework.cloud
    spring-cloud-starter-netflix-hystrix

  2. Define degradation method
    /**
    *Define degradation method:
    * 1. The return value of the method needs to be the same as the original method
    * 2. The parameters of the method need to be the same as the original method
    */
    public Goods findOne_fallback(int id){
    Goods goods = new Goods();
    goods.setTitle("downgraded ~ ~");

            return goods;
        }
    
  3. Use the @ HystrixCommand annotation to configure the degradation method
    /**
    *Downgrade:
    * 1. An exception occurred
    * 2. Service call timeout
    ** default 1s timeout
    *
    * @HystrixCommand(fallbackMethod = "findOne_fallback")
    * fallbackMethod: Specifies the name of the method that is called after downgrading.
    */

        @GetMapping("/findOne/{id}")
        @HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
                //Set the timeout of Hystrix. The default is 1s
                @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    
        })
        public Goods findOne(@PathVariable("id") int id){
    
            //1. Make an exception
            int i = 3/0;
            try {
                //2. Sleep for 2 seconds
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Goods goods = goodsService.findOne(id);
    
            goods.setTitle(goods.getTitle() + ":" + port);//Set the port number to the product title
            return goods;
        }
    
  4. Start the Hystrix function on the startup class: @ enablercircuitbreaker
    package com.itheima.provider;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    /**
     * Startup class
     */
    
    @EnableEurekaClient //This annotation can be omitted in the new version
    @SpringBootApplication
    @EnableCircuitBreaker
    public class ProviderApp {
    
        public static void main(String[] args) {
            SpringApplication.run(ProviderApp.class,args);
        }
    }
    

2.2.2 Hystrix downgrade – service consumer

  1. The feign component has integrated the hystrix component.

  2. Define feign call interface implementation class, replication method, i.e. degradation method
    package com.itheima.consumer.feign;

    import com.itheima.consumer.config.FeignConfig;
    import com.itheima.consumer.domain.Goods;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    /**
     *
     * feign Declarative interface. The that initiated the remote call.
     *
     String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
     Goods goods = restTemplate.getForObject(url, Goods.class);
     *
     * 1. Define interface
     * 2. Add the annotation @ FeignClient on the interface and set the value attribute to the application name of the service provider
     * 3. Write the calling interface, and the declaration rules of the interface shall be consistent with the provider interface.
     * 4. Inject the interface object and call the interface method to complete the remote call
     *
     */
    
    @Component
    public class GoodsFeignClientFallback implements GoodsFeignClient {
    
    
        public Goods findGoodsById(@PathVariable("id") int id){
            Goods goods = new Goods();
            goods.setTitle("Demoted again....");
            return goods;
        };
    
    }
    
  3. Use the fallback attribute in the @ FeignClient annotation to set the degradation processing class
    package com.itheima.consumer.feign;

    import com.itheima.consumer.config.FeignConfig;
    import com.itheima.consumer.domain.Goods;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    /**
     *
     * feign Declarative interface. The that initiated the remote call.
     *
     String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
     Goods goods = restTemplate.getForObject(url, Goods.class);
     *
     * 1. Define interface
     * 2. Add the annotation @ FeignClient on the interface and set the value attribute to the application name of the service provider
     * 3. Write the calling interface, and the declaration rules of the interface shall be consistent with the provider interface.
     * 4. Inject the interface object and call the interface method to complete the remote call
     *
     */
    
    @FeignClient(value = "HYSTRIX-PROVIDER",configuration = FeignConfig.class,fallback = GoodsFeignClientFallback.class)
    public interface GoodsFeignClient {
    
    
        @GetMapping("/goods/findOne/{id}")
        public Goods findGoodsById(@PathVariable("id") int id);
    
    }
    
  4. Configure to enable feign hystrix. enabled = true
    feign:
    hystrix:
    enabled: true

2.3 Hystrix fusing

The Hystrix fuse mechanism is used to monitor the microservice call. When the failure reaches the predetermined threshold (20 failures in 5 seconds), the circuit breaker will be opened and all requests will be rejected until the service returns to normal.

  1. circuitBreaker.sleepWindowInMilliseconds: the monitoring time is 5000 mm by default

  2. circuitBreaker. Requestvolumthreshold: the default number of failures is 20

  3. circuitBreaker.errorThresholdPercentage: the default failure rate is 50

    package com.itheima.provider.controller;

    import com.itheima.provider.domain.Goods;
    import com.itheima.provider.service.GoodsService;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    /**

    • Goods Controller service provider
      */

    @RestController
    @RequestMapping("/goods")
    public class GoodsController {

     @Autowired
     private GoodsService goodsService;
    
     @Value("${server.port}")
     private int port;
    
     @GetMapping("/findOne/{id}")
     @HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
             //Set the timeout of Hystrix. The default is 1s
             @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "2000"),
    

    // @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "2000"),
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "5"),
    // @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "2000")

     })
     public Goods findOne(@PathVariable("id") int id){
    

    // int i = 10/0;
    if (id == 1){
    int i = 10/0;
    }
    Goods goods = goodsService.findOne(id);

         goods.setTitle(goods.getTitle() + ":" + port);//Set the port number to the product title
    

    // try {
    // Thread.sleep(4000);
    // } catch (InterruptedException e) {
    // e.printStackTrace();
    // }
    return goods;
    }

     /**
      * Define degradation method:
      *  1. The return value of the method needs to be the same as the original method
      *  2. The parameters of the method need to be the same as the original method
      */
     public Goods findOne_fallback(int id){
         Goods goods = new Goods();
         goods.setTitle("Demoted~~~");
    
         return goods;
     }
    

    }

2.4 Hystrix fuse monitoring

  1. Hystrix provides the hystrix dashboard function to monitor the running status of microservices in real time.

  2. However, the hystrix dashboard can only monitor one microservice.

  3. Netflix also provides Turbine for aggregation monitoring.

  4. Gateway gateway

3.1 gateway overview

  1. Gateway aims to provide a simple and effective unified API routing management method for microservice architecture
  2. In the microservice architecture, different microservices can have different network addresses. Each microservice completes a user request by calling each other. The client may complete a user request by calling the interfaces of N microservices.
    1. Existing problems:
      1. The client requests different microservices many times, which increases the complexity of the client
      2. Authentication is complex, and every service needs to be authenticated
      3. The number of http requests for different services increases, and the performance is not high
  3. Gateway is the entrance of the system. It encapsulates the internal structure of the application and provides unified services for the client. Some public logic independent of the business function can be implemented here, such as authentication, authentication, monitoring, caching, load balancing, traffic control, routing forwarding, etc
  4. Among the current gateway solutions, there are Nginx+ Lua, Netflix Zuul, Spring Cloud Gateway, etc

Expanded content: the difference between zuul and gateway

3.2 Gateway quick start

To create a gateway provider module:

<?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>gateway-parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway-provider</artifactId>

    <dependencies>

        <!--spring boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <!-- eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!-- hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>




    </dependencies>
</project>

Configuration file application yml:

server:
  port: 8001

eureka:
   client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: gateway-provider

Create gateway consumer:

<?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>gateway-parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway-consumer</artifactId>

    <dependencies>

        <!--spring boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <!-- eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    </dependencies>
</project>

Configuration file application yml:

server:
  port: 9000


eureka:
  instance:
    hostname: localhost # host name
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: gateway-consumer

# Enable feign's support for hystrix
feign:
  hystrix:
    enabled: true
  1. Build gateway module
    Create API gateway server:
    <?xml version="1.0" encoding="UTF-8"?>


    gateway-parent
    com.itheima
    1.0-SNAPSHOT

    4.0.0

        <artifactId>api-gateway-server</artifactId>
    
    
        <dependencies>
            <!--introduce gateway gateway-->
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-gateway</artifactId>
            </dependency>
    
            <!-- eureka-client -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    
  2. Import dependency: starter -gateway

  3. Write startup class
    package com.itheima.gateway;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    @SpringBootApplication
    @EnableEurekaClient
    public class ApiGatewayApp {
    
        public static void main(String[] args) {
            SpringApplication.run(ApiGatewayApp.class,args);
        }
    
    }
    
  4. Write configuration file
    application.yml:
    server:
    port: 80

    spring:
      application:
        name: api-gateway-server
    
      cloud:
        # Gateway configuration
        gateway:
          # Routing configuration: forwarding rules
          routes: #Set.
          # id: unique identification. The default is a UUID
          # uri: forwarding path
          # Predictions: conditions used to request matching rules for gateway paths
          # Filters: to configure local filters
    
          - id: gateway-provider
            # Static routing
            # uri: http://localhost:8001/
            # Dynamic routing
            uri: lb://GATEWAY-PROVIDER
            predicates:
            - Path=/goods/**
            filters:
            - AddRequestParameter=username,zhangsan
    
          - id: gateway-consumer
            # uri: http://localhost:9000
            uri: lb://GATEWAY-CONSUMER
            predicates:
            - Path=/order/**
            # Microservice name configuration
          discovery:
            locator:
              enabled: true # Set to true to add the microservice name before the request path
              lower-case-service-id: true # Lowercase allowed
    
    
    
    
    
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka
    
  5. Start test

Note: the initial letter P of Path must be capitalized, and there must be a space after: and indentation. It must be noted that multiple IDs are one level

3.3 Gateway routing configuration

3.3.1 Gateway gateway routing configuration - static routing

3.3.2 Gateway gateway routing configuration - dynamic routing

  1. Introduce Eureka client configuration
  2. Modify uri attribute: uri: lb: / / service name

3.3.3 Gateway gateway routing configuration - micro service name configuration

spring:
	cloud:
		discovery:
			locator:
				enabled: true # Enable the micro service discovery function
					lower-case-service-id: true # The service name on the request path is configured as lowercase

3.4 Gateway filter

  1. The Gateway supports the filter function to intercept requests or responses and complete some general operations.
  2. Gateway provides two filter modes: "pre" and "post"
  3. The pre filter is implemented before forwarding. It can perform parameter verification, permission verification, traffic monitoring, log output, protocol conversion, etc.
  4. The post filter is executed before the response. It can modify the response content and response header, log output, traffic monitoring, etc.
  5. Gateway also provides two types of filters
    1. Gateway filter: local filter for a single route
    2. GlobalFilter: Global filter for all routes

3.4.1 Gateway filter – local filter

  1. Gateway filter is a local filter for a single route
  2. A large number of built-in local filters are provided in the Spring Cloud Gateway component to filter requests and responses.
  3. Following the idea that the Convention is greater than the configuration, you only need to configure the local filter name in the configuration file and specify the corresponding value to make it effective.
    server:
    port: 80
    spring:
    application:
    name: api-gateway-server
    cloud:
    gateway:
    routes:
    - id: gateway-provider
    #uri: http://localhost:8001
    uri: lb://GATEWAY-PROVIDER
    predicates:
    - Path=/goods/**
    - id: gateway-consumer
    #uri: http://localhost:9000
    uri: lb://GATEWAY-CONSUMER
    predicates:
    - Path=/order/**
    filters:
    - AddRequestParameter=username,aaaa
    - AddRequestHeader=aaaaa,bbbbb
    discovery:
    locator:
    enabled: true
    lower-case-service-id: true
    eureka:
    client:
    service-url:
    defaultZone: http://localhost:8761/eureka

3.4.2 Gateway filter – global filter

  1. GlobalFilter global filter, which does not need to be configured in the configuration file, is loaded during system initialization and acts on each route.
  2. The core functions of Spring Cloud Gateway are also completed through the built-in global filter.
  3. To customize a global filter:
    1. Define classes that implement GlobalFilter and Ordered interfaces

    2. Replication method

    3. Complete logical processing
      package com.itheima.gateway.filter;

      import org.springframework.cloud.gateway.filter.GatewayFilterChain;
      import org.springframework.cloud.gateway.filter.GlobalFilter;
      import org.springframework.core.Ordered;
      import org.springframework.stereotype.Component;
      import org.springframework.web.server.ServerWebExchange;
      import reactor.core.publisher.Mono;
      @Component`Insert the code slice here`
      public class MyFilter implements GlobalFilter, Ordered {
          @Override
          public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
              System.out.println("Global filter...");
              return chain.filter(exchange);
          }
      
          @Override
          public int getOrder() {
              return 1;
          }
      }
      
  • For Gantt chart syntax, refer to here,

UML diagram

UML diagrams can be used for rendering. Mermaid . For example, a sequence diagram is generated as follows:

This will produce a flowchart.:

  • For Mermaid syntax, see here,

FLowchart

We will still support the flowchart of flowchart:

  • For Flowchart syntax, refer to here.

Export and import

export

If you want to try this editor, you can edit it at will in this article. When you have finished writing an article, find the article export in the upper toolbar to generate an article md file or html file for local saving.

Import

If you want to load an article you wrote md file. In the upper toolbar, you can select the import function to import the file with the corresponding extension,
Continue your creation.

  1. mermaid syntax description ↩︎

  2. Explanation of footnotes ↩︎

Topics: Java