feign中开启熔断的书写步骤

/**   1、在pom.xml中引入依赖    2、在application.yaml中开启hystrix

     3、在方法上配置熔断类     4、书写接口的实现类

**/

//1、在pom.xml中引入依赖

<?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>cloud-demo</artifactId>
<groupId>com.hope.demo</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>consumer-demo</artifactId>

<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-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
//2、在application.yaml中开启hystrix
server:
port: 8083
spring:
application:
name: consumer-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka,http://127.0.0.1:10087/eureka
registry-fetch-interval-seconds: 30
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
user-service:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000
ribbon:
ReadTimeout: 6000
ConnectTimeout: 6000
feign:
hystrix:
enabled: true

//3、在方法上配置熔断类
package com.hope.Consumer.client;

import com.hope.Consumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
* @author newcityman
* @date 2019/12/19 - 19:42
*/
@FeignClient(value = "user-service",fallback = UserClientFallback.class )
public interface UserClient {
@GetMapping("user/{id}")
User queryById(@PathVariable("id") Long id);
}

//4、书写接口的实现类

package com.hope.Consumer.client;

import com.hope.Consumer.pojo.User;
import org.springframework.stereotype.Component;

/**
* @author newcityman
* @date 2019/12/19 - 22:52
*/
@Component
public class UserClientFallback implements UserClient {
@Override
public User queryById(Long id) {
User user = new User();
user.setName("未知用户");
return user;
}
}
 
 
posted on 2019-12-19 23:25  小猪_佩奇  阅读(1257)  评论(0编辑  收藏  举报