springboot集成 hystrix

1. 在pom.xml 中 添加依赖

	<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

2. appcation 中开启断路器

@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3. yml 中配置断路器

feign:
  hystrix:
    enabled: true

4. 写本服务调用其他服务的远程接口

package....;
import ...SpareDetail;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;


@Component
@FeignClient(name = "spare",fallback =ConfigServiceHystrix.class)
public interface SpareRemote {

    // 这个路径 是远程接口的路径 我们这里一定要保证 和提供方保持一致     
    @PostMapping("/remote/get-by-ids/")
    List<SpareDetail> getSpareListByIds(@RequestBody  List<String> ids);
}

5. 实现降级方法

先写一个类,一定要加@Component,该类实现上面那个接口,实现里面所有的抽象方法,名字一定要一样,一定要有@Override

package...remote;

import ...SpareDetail;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author  
 * @ClassName: ConfigServiceHystrix
 * @Description: 熔断器
 * @date 2019年9月2日
 */
@Component
public class ConfigServiceHystrix implements  SpareRemote{

    @Override
    public  List<SpareDetail> getSpareListByIds(@RequestBody List<String> ids){
        List<SpareDetail> SpareDetailList = ids.stream().map(id -> {
            SpareDetail sd = new SpareDetail();
            sd.setId(id);
            sd.setSpareName("查询备品数据失败");
            return  sd;
        }).collect(Collectors.toList());
        return SpareDetailList;
    };

}

6 controller 里调用吧

@RestController
public class TestController {
    @Autowired
    private SpareRemote spareRemote;

    @GetMapping("/test")
    public  List<SpareDetail>  test(){
        //根据ids 获取 spareList
        ArrayList<String> ids = new ArrayList<>();
        ids.add("8b483c741c87f1385af4181e85c0c4da");
        ids.add("d6640856e7f40689a52995426cf3d91b");
        // 调取
        List<SpareDetail> spareListByIds = spareRemote.getSpareListByIds(ids);
        return  spareListByIds;
    }

}

7.使用工具测试一下controller提供的接口

直接看结果
[{
“spareId”: “8b483c741c87f1385af4181e85c0c4da”,
“spareName”: “查询备品备件数据失败”
},
{
“spareId”: “d6640856e7f40689a52995426cf3d91b”,
“spareName”: “查询备品备件数据失败”
}]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值