Hystrix集群及监控turbine

Hystrix集群及监控turbine

前面Dashboard演示的仅仅是单机服务监控,实际项目基本都是集群,所以这里集群监控用的是turbine。

turbine是基于Dashboard的

新建一个项目
在这里插入图片描述
导入依赖

<?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>com.yq</groupId>
        <artifactId>microservice</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>microservice-student-provider-hystrix</artifactId>


    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yq</groupId>
            <artifactId>microservice-common</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>

        <!--添加注册中心Eureka相关配置-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <!-- actuator监控引入 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--Hystrix相关依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

yml文件

---
server:
  port: 1004
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-hystrix-1004

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1004
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.yq.com:2001/eureka/,http://eureka2002.yq.com:2002/eureka/,http://eureka2003.yq.com:2003/eureka/

info:
  groupId: com.yq.testSpringcloud
  artifactId: microservice-student-provider-hystrix-1004
  version: 1.0-SNAPSHOT
  userName: http://yq.com
  phone: 123456

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1500

---
server:
  port: 1005
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-hystrix-1005

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1005
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.yq.com:2001/eureka/,http://eureka2002.yq.com:2002/eureka/,http://eureka2003.yq.com:2003/eureka/

info:
  groupId: com.yq.testSpringcloud
  artifactId: microservice-student-provider-hystrix-1005
  version: 1.0-SNAPSHOT
  userName: http://yq.com
  phone: 123456

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1500

---
server:
  port: 1006
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-hystrix-1006

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1006
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.yq.com:2001/eureka/,http://eureka2002.yq.com:2002/eureka/,http://eureka2003.yq.com:2003/eureka/

info:
  groupId: com.yq.testSpringcloud
  artifactId: microservice-student-provider-hystrix-1006
  version: 1.0-SNAPSHOT
  userName: http://yq.com
  phone: 123456

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1500

MicroserviceStudentProviderHystrixApplication

package com.yq.microservicestudentproviderhystrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableCircuitBreaker
@EntityScan("com.yq.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderHystrixApplication {

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

}

这样就有hystrix集群了

新建一个项目
在这里插入图片描述
导入依赖

<?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>com.yq</groupId>
        <artifactId>microservice</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>microservice-student-consumer-hystrix-turbine-91</artifactId>
   

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

yml文件

server:
  port: 91
  context-path: /
eureka:
  client:
    service-url:
      defaultZone: http://eureka2001.yq.com:2001/eureka/,http://eureka2002.yq.com:2002/eureka/,http://eureka2003.yq.com:2003/eureka/
turbine:
  app-config: microservice-student   # 指定要监控的应用名称
  clusterNameExpression: "'default'" #表示集群的名字为default
spring:
  application:
    name: turbine

MicroserviceStudentConsumerHystrixTurbine91Application

package com.yq.microservicestudentconsumerhystrixturbine91;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableTurbine
public class MicroserviceStudentConsumerHystrixTurbine91Application {

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

}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Feign、Hystrix整合

前面的代码,用@HystrixCommand fallbackMethod是很不好的,因为和业务代码耦合度太高,不利于维护,所以需要解耦,这我们讲下Feign Hystrix整合。
StudentService

package com.yq.microservicestudentproviderhystrix.service;

import com.yq.microservicecommon.entity.Student;

import java.util.List;
import java.util.Map;

public interface StudentService {
 
    public void save(Student student);
     
    public Student findById(Integer id);
     
    public List<Student> list();
     
    public void delete(Integer id);

    public Map<String,Object> hystrix();
     
     
}


StudentServiceImpl

package com.yq.microservicestudentproviderhystrix.service;

import com.yq.microservicecommon.entity.Student;

import com.yq.microservicestudentproviderhystrix.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 陌陌
 * @create  2020-01-08 14:56
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Value("${server.port}")
    private Integer port;

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void save(Student student) {
        studentRepository.save(student);
    }

    @Override
    public Student findById(Integer id) {
        return studentRepository.findOne(id);
    }

    @Override
    public List<Student> list() {
        return studentRepository.findAll();
    }

    @Override
    public void delete(Integer id) {
        studentRepository.delete(id);
    }

    @Override
    public Map<String, Object> hystrix() {
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code", 200);
        map.put("info","工号【"+port+"】正在为您服务");
        return map;
    }
}


StudentProviderController

package com.yq.microservicestudentproviderhystrix.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yq.microservicecommon.entity.Student;
import com.yq.microservicestudentproviderhystrix.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentProviderController {

    @Autowired
    private StudentService studentService;

    @PostMapping(value="/save")
    public boolean save(Student student){
        try{
            studentService.save(student);
            return true;
        }catch(Exception e){
            return false;
        }
    }

    @GetMapping(value="/list")
    public List<Student> list(){
        return studentService.list();
    }

    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable("id") Integer id){
        return studentService.findById(id);
    }

    @GetMapping(value="/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id){
        try{
            studentService.delete(id);
            return true;
        }catch(Exception e){
            return false;
        }


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

    @RequestMapping("/ribbon")
    public String ribbon(){
        return "工号【"+port+"】正在为您服务";
    }


    /**
     * 测试Hystrix服务降级
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping(value="/hystrix")
//    @HystrixCommand(fallbackMethod="hystrixFallback")
    public Map<String,Object> hystrix() throws InterruptedException{
        Thread.sleep(2000);
//        Map<String,Object> map=new HashMap<String,Object>();
//        map.put("code", 200);
//        map.put("info","工号【"+port+"】正在为您服务");
//        return map;
        return this.studentService.hystrix();
    }

//    public Map<String,Object> hystrixFallback() throws InterruptedException{
//        Map<String,Object> map=new HashMap<String,Object>();
//        map.put("code", 500);
//        map.put("info", "系统【"+port+"】繁忙,稍后重试");
//        return map;
//    }

}




StudentClientService

package com.yq.microservicecommon.service;


import com.yq.microservicecommon.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

/**
 * Student Feign接口客户端
 * @author Administrator
 *
 */
@FeignClient(value="MICROSERVICE-STUDENT",fallbackFactory = StudentClientFallbackFactory.class)
public interface StudentClientService {
 
    /**
     * 根据id查询学生信息
     * @param id
     * @return
     */
    @GetMapping(value="/student/get/{id}")
    public Student get(@PathVariable("id") Integer id);
     
    /**
     * 查询学生信息
     * @return
     */
    @GetMapping(value="/student/list")
    public List<Student> list();
     
    /**
     * 添加或者修改学生信息
     * @param student
     * @return
     */
    @PostMapping(value="/student/save")
    public boolean save(Student student);
     
    /**
     * 根据id删除学生信息
     * @return
     */
    @GetMapping(value="/student/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id);

    @RequestMapping("/student/ribbon")
    public String ribbon();

    /**
     * 服务熔断降级
     * @return
     */
    @GetMapping(value="/student/hystrix")
    public Map<String,Object> hystrix();
}

StudentClientFallbackFactory

package com.yq.microservicecommon.service;


import com.yq.microservicecommon.entity.Student;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class StudentClientFallbackFactory implements FallbackFactory<StudentClientService> {

    @Override
    public StudentClientService create(Throwable cause) {
        return new StudentClientService() {

            @Override
            public boolean save(Student student) {
                return false;
            }

            @Override
            public List<Student> list() {
                return null;
            }

            @Override
            public Map<String, Object> hystrix() {
                Map<String,Object> map=new HashMap<String,Object>();
                map.put("code", 500);
                map.put("info", "系统繁忙,稍后重试");
                return map;
            }

            @Override
            public Student get(Integer id) {
                return null;
            }

            @Override
            public boolean delete(Integer id) {
                return false;
            }

            @Override
            public String ribbon() {
                return null;
            }
        };
    }

}

这样我们实现了 降级处理方法

修改microservice-student-consumer-feign-80 支持Hystrix

StudentConsumerController

package com.yq.microservicestudentconsumerfeign80.controller;


import com.yq.microservicecommon.entity.Student;
import com.yq.microservicecommon.service.StudentClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentConsumerController {

    @Autowired
    private StudentClientService studentClientService;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping(value = "/save")
    private boolean save(Student student) {
        return studentClientService.save(student);
    }

    @GetMapping(value = "/list")
    public List<Student> list() {
        return studentClientService.list();
    }

    @GetMapping(value = "/get/{id}")
    public Student get(@PathVariable("id") Integer id) {
        return studentClientService.get(id);
    }

    @GetMapping(value = "/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id) {
        try {
            studentClientService.delete(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @RequestMapping("/ribbon")
    public String ribbon(){
        return studentClientService.ribbon();
    }

    /**
     * Feign整合Hystrix服务熔断降级
     * @return
     * @throws InterruptedException
     */
    @GetMapping(value="/hystrix")
    public Map<String,Object> hystrix() throws InterruptedException{
        return studentClientService.hystrix();
    }
}

yml文件

server:
  port: 80
  context-path: /
eureka:
  client:
    service-url:
      defaultZone: http://eureka2001.yq.com:2001/eureka/,http://eureka2002.yq.com:2002/eureka/,http://eureka2003.yq.com:2003/eureka/
    register-with-eureka: false

feign:
  hystrix:
    enabled: true

MicroserviceStudentConsumerFeign80Application

package com.yq.microservicestudentconsumerfeign80;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

@EnableEurekaClient
@EnableFeignClients(value = "com.yq.*.*")
@ComponentScan(basePackages = {"com.yq.microservicecommon","com.yq.microservicestudentconsumerfeign80"})
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumerFeign80Application {

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

}

注意:
公共子项目与当前子项目的基包都要扫描到;
只指定公共子模块为基包会导致本子项目的springmvc功能失效;
只指定本子项目为基包会导致feign与Hystrix集成失败,从而导致服务熔断功能失效

这是正常的但是还是有问题的

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

集群后超时设置

在microservice-student-consumer-feign-80上加个 ribbon超时时间设置

yml文件

server:
  port: 80
  context-path: /
eureka:
  client:
    service-url:
      defaultZone: http://eureka2001.yq.com:2001/eureka/,http://eureka2002.yq.com:2002/eureka/,http://eureka2003.yq.com:2003/eureka/
    register-with-eureka: false

feign:
  hystrix:
    enabled: true

ribbon:
  ReadTimeout: 10000
  ConnectTimeout: 9000
  
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1500

1005和1006是失败的,只有1004是成功的
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值