1. 程式人生 > >spring cloud(斷路器——初學五)

spring cloud(斷路器——初學五)

int integer ons ref 配置文件 ping stp -1 ges

Feign使用Hystrix

  因為feign已經依賴了hystrix,所以可以直接使用,無需添加再次添加依賴。

  1、使用@FeignClient註解中的fallback屬性指定回調類

package com.daqsoft;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; /** * @Description Created by liaoxx on 2017-6-12. */ @FeignClient(value = "compute-service", fallback = ComputeClientHystrix.class) public interface ComputerClient { @RequestMapping(method = RequestMethod.GET, value = "/add") Integer add(@RequestParam(value
= "a") Integer a, @RequestParam(value = "b") Integer b); }

  2、創建回調類ComputeClientHystrix,實現@FeignClient的接口,此時實現的方法就是對應@FeignClient接口中映射的fallback函數

package com.daqsoft;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Description Created by liaoxx on 2017-6-13.
 
*/ @Component public class ComputeClientHystrix implements ComputerClient { @Override public Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b) { return -1; } }

  3、web調用

package com.daqsoft;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description Created by liaoxx on 2017-6-12.
 */
@RestController
public class CustomController {

    @Autowired
    private ComputerClient computerClient;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public Integer add(){
        return computerClient.add(10,20);

    }
}

  4、啟動服務,訪問http://localhost:3333/add

  技術分享

  報錯,無法進入回調

  5、修改配置文件,添加屬性

spring.application.name=ribbon-consumer

server.port=3333
#服務註冊中心地址
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

#開啟hystrix支持 feign.hystrix.enabled=true

  6、再次啟動服務,訪問http://localhost:3333/add (正常訪問回調方法)

  技術分享

  

spring cloud(斷路器——初學五)