天天看點

springcloud 簡單示例之斷路器hystrix(六)

在分布式系統中,為了保證其高可用,單個服務有時候會叢集部署,由于網絡或程式的原因,服務并不能保證百分百可靠可用,如果單個服務出現問題,調用這個服務就出現線程阻塞,此時若有大量的請求湧入,servlet容器的線程資源就會被消耗完畢導緻服務癱瘓。

為了解決這個問題,有人就提出了一種解決問題的思路,斷路器模型。就是每一個調用服務的接口處加一個斷路器,預設是關閉的,當對服務調用時,不可用的次數達到一個閥值時,斷路器就會打開,通過回調方法迅速傳回一個值結束調用,避免出現連鎖故障。

1.ribbon+restTemplate方式

在pom中追加引用

<!-- ribbon時的hystrix斷路器調用時使用 -->
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
      </dependency>
           

修改java程式

package com.dongjin.springcloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@EnableHystrix
@RestController
public class RibbonHiController {
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
	    return new RestTemplate();
	}

	@Autowired
	private RestTemplate restTemplate;

	@RequestMapping("/RibbonHello")
	@HystrixCommand(fallbackMethod = "helloError")
	public String hello(String name){
	    String result=restTemplate.getForObject("http://springcloud-user/hi", String.class);
	    return result;
	}
	
	public String helloError() {
	      return "hello!  sorry ,error !";
	}
}
           

當關掉7002的服務時,頁面立馬出現傳回

springcloud 簡單示例之斷路器hystrix(六)

2.feign方式

feign中自帶了斷路器hystrix,無需再次引用,直接打開就可以

springcloud 簡單示例之斷路器hystrix(六)

修改java代碼

package com.dongjin.springcloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@EnableDiscoveryClient
@EnableFeignClients
@RestController
public class FeiHiController {
    
    @FeignClient(value = "springcloud-user", fallback = HelloError.class)
    public interface FeiHiService {
        @RequestMapping(value = "/hi")
        String sayHi();
    }
    
    @Component
    public class HelloError implements FeiHiService {
    	@Override
    	public String sayHi() {
    		return "hello!  sorry ,error !";
    	}
    }
    
    @Autowired
    FeiHiService hiService;
    
    @RequestMapping("/FeiHello")
    public String sayHello(String name){
        String word = hiService.sayHi();
        return word;
    }
}
           

當關掉7002的服務時,頁面立馬出現傳回

springcloud 簡單示例之斷路器hystrix(六)

繼續閱讀