博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第八章 SpringCloud之Feign、Hystrix结合使用
阅读量:5139 次
发布时间:2019-06-13

本文共 9495 字,大约阅读时间需要 31 分钟。

#这个章节主要是针对Hystrix的使用,因为Feign的章节在上一节已经实现了,整个代码也是在上一个章节的基础上修改的

##################Hystrix一个简单Demo实现#######################

1、pom.xml

4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE
com.test
eureka-client-feign-hystrix
0.0.1-SNAPSHOT
eureka-client-feign-hystrix
Demo project for Spring Boot
1.8
Greenwich.SR1
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
View Code

2、application.yml文件配置

spring:  application:    name: eureka-client-feign-hystrix  #应用名logging:  #logging日志配置  level:    root: INFO    org.hibernate: INFOserver:  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

3、启动类加配置

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@EnableCircuitBreakerpublic class EurekaClientFeignHystrixApplication {    public static void main(String[] args) {        SpringApplication.run(EurekaClientFeignHystrixApplication.class, args);    }}

4、User.java类

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

5、自定义UserFeignClientConfig.java类,该类的使用,表示不使用Feign的默认配置

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

6、UserFeignClient1.java

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);}

7、MovieController.java类,实现远程调用的类

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;@RestControllerpublic 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;    }}

8、URL访问

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;@RestControllerpublic 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健康检查与监控################

1、在pom.xml再添加下面依赖

org.springframework.boot
spring-boot-starter-actuator

2、在启动类添加一个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@EnableCircuitBreakerpublic 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;    }}

3、启动Eureka和服务程序,访问远程调用的服务程序,执行下面的URL

#使用了actuator,所以都必须以这个组件开始http://localhost:8667/actuator/hystrix.streamhttp://localhost:8667/actuator/health

 

转载于:https://www.cnblogs.com/ywjfx/p/10556521.html

你可能感兴趣的文章
JavaScript面向对象初探——封装和继承
查看>>
L2-001 紧急救援 (dijkstra+dfs回溯路径)
查看>>
javascript 无限分类
查看>>
spring IOC装配Bean(注解方式)
查看>>
[面试算法题]有序列表删除节点-leetcode学习之旅(4)
查看>>
SpringBoot系列五:SpringBoot错误处理(数据验证、处理错误页、全局异常)
查看>>
kubernetes_book
查看>>
OpenFire 的安装和配置
查看>>
ZJOI2018游记Round1
查看>>
侧边栏广告和回到顶部
查看>>
https://blog.csdn.net/u012106306/article/details/80760744
查看>>
ios应用版本号设置规则
查看>>
海上孤独的帆
查看>>
error: more than one device and emulator 问题解决
查看>>
Java基础:容器
查看>>
YUV摘要格式
查看>>
【方法2】删除Map中Value反复的记录,而且仅仅保留Key最小的那条记录
查看>>
C# CheckedListBox控件的使用方法
查看>>
【HDOJ】2007平方和与立方和
查看>>
js中const,var,let区别
查看>>