Spring cloud project integration [eureka+ribbon+zuul+hystrix+hystrix dashboard]

Keywords: Maven Spring Mybatis Apache

This article is not suitable for people who do not have the foundation of spring cloud.
This article is a shelf that I sorted out after learning spring cloud. Mainly for self study
Students who need source code are concerned about the following official account reply: xdxcloud



Service Architecture





1. Create parent project

1-1: create project


1-2: add pom 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>www.xdx97.cloud</groupId>
    <artifactId>xdxcloud</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <springboot.mybatis.version>2.0.1</springboot.mybatis.version>
        <mybatis-plus-boot-starter.version>3.0.2</mybatis-plus-boot-starter.version>
        <springboot.pagehelper.version>1.2.3</springboot.pagehelper.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.18.2</lombok.version>
        <druid.version>1.1.10</druid.version>
        <mysql.connector.version>5.1.45</mysql.connector.version>
        <jackson.version>2.10.1</jackson.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- Spring Cloud rely on -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- Spring Boot rely on -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.0.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- MySQL Connection driven dependency -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.connector.version}</version>
            </dependency>
            <!-- Spring Boot Mybatis rely on -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${springboot.mybatis.version}</version>
            </dependency>
            <!-- Spring Boot Mybatis Enhanced plug-in -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis-plus-boot-starter.version}</version>
            </dependency>
            <!-- mysql Database connection pool pool -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.10</version>
            </dependency>
            <!-- MyBatis Paging plugins -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>${springboot.pagehelper.version}</version>
            </dependency>
            <!-- lombok Plug-in unit -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
            <!-- log4j rely on -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <!-- @JsonFormat Use of annotations -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.10.1</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

2. Set up and configure eureka cluster

2-1: create maven project (refer to this for later maven projects)

2-3: created in the same way as above, eureka-7002

2-4: configure pom.xml

2-4-1: eureka-7001
<?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>xdxcloud</artifactId>
        <groupId>www.xdx97.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eureka-7001</artifactId>

    <dependencies>
        <!-- eureka Server Server side -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>
2-4-2: eureka-7002
<?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>xdxcloud</artifactId>
        <groupId>www.xdx97.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eureka-7002</artifactId>
    
    <dependencies>
        <!-- eureka Server Server side -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

2-5. Create startup class

2-5-1: EurekaServer7001
package com.xdx97.cloud;

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

@SpringBootApplication
@EnableEurekaServer
public class EurekaServer7001 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer7001.class,args);
    }
}

2-5-1: similarly create EurekaServer7002

2-6 configure domain name mapping


Add the following code at the end and save.

127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com

2-7: create application.yml

2-7-1: 7001 application.yml
server:
    port: 7001

eureka:
    instance:
        hostname: eureka7001.com   # Instance name of eureka server
    client:
        register-with-eureka: false     #false means that you do not register yourself with the registry
        fetch-registry: false  #false means that my client is the registry. My responsibility is to maintain the service instance. I don't need to retrieve the service
        service-url:
            #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka / ා stand alone setting Eureka Server interactive address query service and registration service
            defaultZone: http://eureka7002.com:7002/eureka/    # Cluster version setup Eureka Server interactive address query service and registration service
2-7-2: 7001 application.yml
server:
    port: 7002

eureka:
    instance:
        hostname: eureka7002.com   # Instance name of eureka server
    client:
        register-with-eureka: false     #false means that you do not register yourself with the registry
        fetch-registry: false  #false means that my client is the registry. My responsibility is to maintain the service instance. I don't need to retrieve the service
        service-url:
            #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka / ා set Eureka Server interactive address query service and registration service
            defaultZone: http://eureka7001.com:7001/eureka/    # Cluster version setup Eureka Server interactive address query service and registration service

2-8 test eureka cluster

2-8-1 start two eureka services
2-8-2 visit http://eureka7001.com:7001/


3. Create public API section

3-1: use the above method to create a maven project named cloud API

3-2: pom 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>xdxcloud</artifactId>
        <groupId>www.xdx97.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-api</artifactId>

    <dependencies>
        <!-- lombok Plug-in unit -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- Spring Boot Mybatis rely on -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${springboot.mybatis.version}</version>
        </dependency>
        <!-- Spring Boot Mybatis Enhanced plug-in -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>
        <!-- @JsonFormat Use of annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>
</project>

3-3: create User entity

Here I use the lombok, MybatisPlus and @ JsonFormat plug-ins. maven has introduced

package com.xdx97.cloud.entitys;

import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Date;

@Data
@Accessors(chain = true)
public class User implements Serializable {
    /**
     * User id
     */
    @TableId
    private String userId;

    /**
     * User name
     */
    private String userName;

    /**
     * User mobile number
     */
    private String userPhone;

    /**
     * Role id
     */
    private String roleId;

    /**
     * User password
     */
    private String userPassword;

    /**
     * Encrypted salt
     */
    private String salt;

    /**
     * openid
     */
    private String openid;

    /**
     * User status: 1 enable 0 disable
     */
    private Byte userStatus;

    /**
     * Avatar path
     */
    private String headImgPath;

    /**
     * Creation time
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date gmtCreate;

    /**
     * Modification time
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date gmtModified;

    /**
     * Founder
     */
    private String userCreate;

    /**
     * Modifier
     */
    private String userModified;

    private static final long serialVersionUID = 1L;
}


4. Create a database

CREATE TABLE `user` (
  `user_id` char(18) NOT NULL COMMENT 'user id',
  `user_name` varchar(50) NOT NULL COMMENT 'User name',
  `user_phone` varchar(20) NOT NULL COMMENT 'User mobile number',
  `role_id` char(18) NOT NULL COMMENT 'role id',
  `user_password` char(40) NOT NULL COMMENT 'User password',
  `salt` char(10) NOT NULL COMMENT 'Encrypted salt',
  `openid` varchar(50) NOT NULL DEFAULT '' COMMENT 'openid',
  `user_status` tinyint(4) NOT NULL COMMENT 'User status:1 Enable 0 disable',
  `head_img_path` varchar(100) NOT NULL DEFAULT '' COMMENT 'Avatar path',
  `gmt_create` datetime NOT NULL COMMENT 'Creation time',
  `gmt_modified` datetime DEFAULT NULL COMMENT 'Modification time',
  `user_create` char(18) NOT NULL COMMENT 'Founder',
  `user_modified` char(18) DEFAULT NULL COMMENT 'Modifier',
  PRIMARY KEY (`user_id`) USING BTREE,
  KEY `id` (`user_name`,`user_phone`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='User table';

5. Create service provider

5-1: create a Maven project, project name: cloud-user-8001

5-2: pom 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>xdxcloud</artifactId>
        <groupId>www.xdx97.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-user-8001</artifactId>

    <dependencies>
        <!-- Introduce api General package -->
        <dependency>
            <groupId>www.xdx97.cloud</groupId>
            <artifactId>cloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- MySQL Connection driven dependency -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- Spring Boot rely on -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <!-- Spring Boot Mybatis Enhanced plug-in -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <!-- mysql Database connection pool pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <!-- MyBatis Paging plugins -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
        </dependency>
        <!-- SpringBoot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Eureka Clien Client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- Perfect monitoring information -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Add to Hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

    </dependencies>

</project>

5-3: configure the yml file

server:
  port: 8001

mybatis:
  type-aliases-package: com.xdx97.cloud.entitys         # Package of all Entity alias classes
  mapper-locations: classpath*:mappers/**/*Mapper.xml   # mapper Map file - classpath:mybatis/mapper/**/*.xml


spring:
    application:
      name: xdxcloud-user
    datasource:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/xdx_cloud?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
      username: root
      password: 123456
      dbcp2:
        min-idle: 5                                # Database connection pool minimum number of maintained connections
        initial-size: 5                           # Number of initial connections
        max-total: 5                               # maximum connection
        max-wait-millis: 200                  # Maximum timeout waiting for link acquisition

# Register services with eureka
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka    # Set Eureka Server interactive address query service and registration service
  instance:
    instance-id: xdxcloud-user8001-hystrix     # Modify the name registered to the eureka service
    prefer-ip-address: true           # Access path can display ip


# Configure info information
info:
  app.name: xdxcloud
  company.name: www.xdx97.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

5-4: configure startup class

package com.xdx97.cloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableEurekaClient             // After the service is started, it will be automatically registered in eureka
@EnableDiscoveryClient          // Service discovery
@EnableCircuitBreaker           //
public class UserApp8001 {
    public static void main(String[] args) {

        SpringApplication.run(UserApp8001.class,args);
    }
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

5-5: configure a basic query

5-5-1: configure mapper
package com.xdx97.cloud.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xdx97.cloud.entitys.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * Inheriting this BaseMapper is the function of MybatisPlus
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

}

Because I only need 2 simple query methods here, I just use MybatisPlus to complete it

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xdx97.cloud.mapper.UserMapper">

</mapper>

5-5-2: Configure service


UserService

package com.xdx97.cloud.service;

import com.xdx97.cloud.entitys.User;

import java.util.List;

public interface UserService {

    List<User> selectList();

    User getById(String id);
}

UserServiceImpl

package com.xdx97.cloud.service.impl;

import com.xdx97.cloud.entitys.User;
import com.xdx97.cloud.mapper.UserMapper;
import com.xdx97.cloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectList() {

        List<User> xUsers = userMapper.selectList(null);
        System.out.println("This is service 8001");
        return xUsers;
    }

    @Override
    public User getById(String id) {

        User user = userMapper.selectById(id);
        return user;
    }
}
5-5-2: configure controller
package com.xdx97.cloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xdx97.cloud.entitys.User;
import com.xdx97.cloud.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserServiceImpl userServiceImpl;

    @GetMapping("/user/list")
    public List<User> list(){
        return userServiceImpl.selectList();
    }

    /**
     *  @HystrixCommand
     *  This is a service fault-tolerant processing of hystrix. Of course, when the method is abnormal, call processhystrix? Get method
     */
    @GetMapping("/user/getById/{id}")
    @HystrixCommand(fallbackMethod = "processHystrix_Get")
    public User getById(@PathVariable("id")  String id){
        System.out.println("id = " + id);
        User user = userServiceImpl.getById(id);
        if (user == null){
            throw new  RuntimeException("Abnormal test!");
        }
        return user;
    }


   public User processHystrix_Get(@PathVariable("id") String id) {
        System.out.println("It's abnormal~~~~");
        User user = new User().setUserName("There's something wrong with the report!!!");
        return user;
    }
}
5-5-3: Test

1. Start two eureka s before starting the 8001 service


2. Let's test the fuse service of hysrix, that is, when the access is abnormal, there is only one data with id=1 in my current database


6. Create zuul routing gateway

6-1: create a maven project: cloud-zuul-9527

6-2: pom 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>xdxcloud</artifactId>
        <groupId>www.xdx97.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-zuul-9527</artifactId>

    <dependencies>
        <!-- Introduce api General package -->
        <dependency>
            <groupId>www.xdx97.cloud</groupId>
            <artifactId>cloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- SpringBoot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Eureka Clien Client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- Perfect monitoring information -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Add to Hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!-- Add to zuul rely on -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
    </dependencies>

</project>

6-3: configure the yml file

server:
    port: 9527

spring:
  application:
    name:  xdx-cloud-zuul

eureka:
    instance:
      instance-id: gateway-9527.com
      prefer-ip-address: true
    client:
        service-url:
            #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka / ා stand alone setting Eureka Server interactive address query service and registration service
            defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7002.com:7002/eureka/

zuul:
  routes:
    myuser.serviceId: xdxcloud-user
    myuser.path: /myuser/**
  #ignored-services: xdxcloud-user        # Do not allow access to a single using a real microservice name
  ignored-services: "*"               # Do not allow access to all using real microservice name
  prefix: /xdx                          # Set the same access prefix

# Configure info information
info:
  app.name: xdxcloud
  company.name: www.xdx97.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

6-4: configure domain name mapping

127.0.0.1 myzuul.com

6-5: configure startup class

package com.xdx97.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableZuulProxy
public class ZuulApp_9527 {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApp_9527.class, args);
    }
}

6-6: testing

Open in the following order

http://myzuul.com:9527/xdx/myuser/user/getById/1




7. Use zuul to configure [service degradation]

Service degradation: simply understand that when a service hangs up, give an emergency response

UserFallback

package com.xdx97.cloud.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class UserFallback implements FallbackProvider {
    @Override
    public String getRoute() {
        // Downgrade all microservices
		return "*";
        // Demote only the specified microservice
        // return "XDXCLOUD-USER";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        System.out.println("route = " + route);

        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                // Return status constant
                return HttpStatus.SERVICE_UNAVAILABLE;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                // Return status code, 503 here
                return HttpStatus.SERVICE_UNAVAILABLE.value();
            }

            @Override
            public String getStatusText() throws IOException {
                // Return the status phrase corresponding to the status code, which is "Service Unavailable"
                return HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase();
            }

            @Override
            public void close() { }

            @Override
            public InputStream getBody() throws IOException {
                // Set degradation information
                // String msg = "fallback:" + ConsumerFallback.this.getRoute();
                String msg = "fallback:" + route;
                return new ByteArrayInputStream(msg.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                // Set degradation response header information
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}

test

1. Turn on all services and access

http://myzuul.com:9527/xdx/myuser/user/getById/1

2. Then we shut down the 8001 service and visit it again


8. Load balancing with a service provider

8-1: create a Maven project: cloud-user-8002

Copy all contents of cloud-user-8001 to 8002

Make the following modifications:

Test: start the program in sequence

Visit this address repeatedly and go to the console to find out that it is polling to call 8001 and 8002 services (zuul uses ribbon's load balancing, and the default is polling algorithm)


9. Create Hyscrix Dashboard monitoring

9-1: create a Maven project: cloud-hysrix-dashboard-9001

9-2: pom 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>xdxcloud</artifactId>
        <groupId>www.xdx97.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-hysrix-dashboard-9001</artifactId>

    <dependencies>
        <!-- Add to Hystrix Dashboard -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
    </dependencies>

</project>

9-3: application.yml

server:
    port: 9001

9-4: startup class

package com.xdx97.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableHystrixDashboard
public class HystrixDashboardApp {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardApp.class, args);
    }
}

9-4: testing

1. Turn on the following services in turn

2. Visit http://localhost:9001/hystrix to see the following screenshot, indicating that the opening is successful

3,http://127.0.0.1:8001/hystrix.stream

4. Then we visit http://myzul.com: 9527 / xdx / myuser / user / getbyid / 1


5. If you want to monitor an interface, you need to configure @ HystrixCommand annotation on the interface

Published 312 original articles, praised 138, visited 560000+
His message board follow

Posted by wiccan8888 on Fri, 14 Feb 2020 02:47:10 -0800