第八章 SpringCloud之Feign、Hystrix結合使用

#這個章節主要是針對Hystrix的使用,由於Feign的章節在上一節已經實現了,整個代碼也是在上一個章節的基礎上修改的java

##################Hystrix一個簡單Demo實現#######################web

一、pom.xmlspring

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.test</groupId>
    <artifactId>eureka-client-feign-hystrix</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-client-feign-hystrix</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

</project>
View Code

二、application.yml文件配置數據庫

spring: application: name: eureka-client-feign-hystrix #應用名 logging: #logging日誌配置 level: root: INFO org.hibernate: INFO server: port: 8667 #服務端口 eureka: instance: hostname: localhost prefer-ip-address: true instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}} client: serviceUrl: defaultZone: http://${eureka.instance.hostname}:8661/eureka

三、啓動類加配置apache

package com.test.eurekaclientfeign; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients @EnableCircuitBreaker public class EurekaClientFeignHystrixApplication { public static void main(String[] args) { SpringApplication.run(EurekaClientFeignHystrixApplication.class, args); } }

四、User.java類app

package com.test.eurekaclientfeign.entity; import java.io.Serializable; import java.math.BigDecimal; public class User implements Serializable { private Long id; private String name; private String username; private BigDecimal balance; private  short age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public short getAge() { return age; } public void setAge(short age) { this.age = age; } }
View Code

五、自定義UserFeignClientConfig.java類,該類的使用,表示不使用Feign的默認配置maven

package com.test.eurekaclientfeign.feign; import feign.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class UserFeignClientConfig { /* @Bean public Contract feignContract() { return new feign.Contract.Default(); }*/ @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } }

六、UserFeignClient1.javaide

package com.test.eurekaclientfeign.feign; import com.test.eurekaclientfeign.entity.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name = "eureka-client-user", configuration = UserFeignClientConfig.class) public interface UserFeignClient1 { @RequestMapping(method = RequestMethod.GET, value = "/user/{id}") User findById(@PathVariable("id") Long id); }

七、MovieController.java類,實現遠程調用的類spring-boot

package com.test.eurekaclientfeign.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.test.eurekaclientfeign.entity.User; import com.test.eurekaclientfeign.feign.UserFeignClient1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MovieController { @Autowired(required = true) private UserFeignClient1 userFeignClient1; @GetMapping(value = "/hystrix/{id}") @HystrixCommand(fallbackMethod = "defaultMethod") //一但沒法調用遠程的findById(),則會調用Hystrix的默認接口defaultMethod(),其參數要一致,不然沒法使用
    public User findById(@PathVariable("id") Long id) { return this.userFeignClient1.findById(id); } public User defaultMethod(@PathVariable("id") Long id){ User user = new User(); user.setId(id); user.setName("hystrix"); return user; } }

八、URL訪問ui

http://localhost:8661/ # 服務發現
http://192.168.137.1:8667/hystrix/9 #實現斷路,由於數據庫沒有id=9的數據
http://192.168.137.1:8667/hystrix/1 #能夠正常訪問

Hystrix訪問實現以下:

 

########Hystrix將調用訪問和斷路執行方法綁定在一個線程#########

只需在MovieController.java中的HystrixCommand添加一個commandProperties屬性便可,以下

package com.test.eurekaclientfeign.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import com.test.eurekaclientfeign.entity.User; import com.test.eurekaclientfeign.feign.UserFeignClient1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MovieController { @Autowired(required = true) private UserFeignClient1 userFeignClient1; @GetMapping(value = "/hystrix/{id}")  @HystrixCommand(fallbackMethod = "defaultMethod", commandProperties = { @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE") } ) //一但沒法調用遠程的findById(),則會調用Hystrix的默認接口defaultMethod(),其參數要一致,不然沒法使用 //添加commandProperties屬性,能夠使得findById()和defaultMethod()綁定到一個線程中
    public User findById(@PathVariable("id") Long id) { return this.userFeignClient1.findById(id); } public User defaultMethod(@PathVariable("id") Long id){ User user = new User(); user.setId(id); user.setName("hystrix"); return user; } }

 

###########Hystrix健康檢查與監控################

一、在pom.xml再添加下面依賴

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

二、在啓動類添加一個Bean

package com.test.eurekaclientfeign; 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.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; @SpringBootApplication @EnableFeignClients @EnableCircuitBreaker public class EurekaClientFeignHystrixApplication { public static void main(String[] args) { SpringApplication.run(EurekaClientFeignHystrixApplication.class, args); }  @Bean public ServletRegistrationBean getServlet(){ HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/actuator/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; } }

三、啓動Eureka和服務程序,訪問遠程調用的服務程序,執行下面的URL

#使用了actuator,因此都必須以這個組件開始 http://localhost:8667/actuator/hystrix.stream
 http://localhost:8667/actuator/health
相關文章
相關標籤/搜索