1. 程式人生 > >dubbo高可用:叢集容錯(十四)

dubbo高可用:叢集容錯(十四)

在叢集呼叫失敗時,Dubbo 提供了多種容錯方案,預設為 failover 重試。

Failover Cluster

失敗自動切換,當出現失敗,重試其它伺服器。通常用於讀操作,但重試會帶來更長延遲。可通過 retries="2" 來設定重試次數(不含第一次)

重試次數配置如下:

<dubbo:service retries="2" />

<dubbo:reference retries="2" />

<dubbo:reference>

    <dubbo:method name="findFoo" retries="2" />

</dubbo:reference>

Failfast Cluster

快速失敗,只發起一次呼叫,失敗立即報錯。通常用於非冪等性的寫操作,比如新增記錄。

Failsafe Cluster

失敗安全,出現異常時,直接忽略。通常用於寫入審計日誌等操作。

Failback Cluster

失敗自動恢復,後臺記錄失敗請求,定時重發。通常用於訊息通知操作。

Forking Cluster

並行呼叫多個伺服器,只要一個成功即返回。通常用於實時性要求較高的讀操作,但需要浪費更多服務資源。可通過 forks="2" 來設定最大並行數。

Broadcast Cluster

廣播呼叫所有提供者,逐個呼叫,任意一臺報錯則報錯 [2]。通常用於通知所有提供者更新快取或日誌等本地資源資訊。

叢集模式配置

按照以下示例在服務提供方和消費方配置叢集模式

<dubbo:service cluster="failsafe" />

<dubbo:reference cluster="failsafe" />

整合hystrix

Hystrix 旨在通過控制那些訪問遠端系統、服務和第三方庫的節點,從而對延遲和故障提供更強大的容錯能力。Hystrix具備擁有回退機制和斷路器功能的執行緒和訊號隔離,請求快取和請求打包,以及監控和配置等功能

spring boot官方提供了對hystrix的整合,直接在服務提供者和消費者的pom.xml里加入依賴:

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

然後在Application類上增加@EnableHystrix來啟用hystrix starter:

@SpringBootApplication
@EnableHystrix
public class ProviderApplication {

配置Provider端

在Dubbo的Provider上增加@HystrixCommand配置,這樣子呼叫就會經過Hystrix代理。

@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
    @HystrixCommand(commandProperties = {
     @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
     @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000") })
    @Override
    public String sayHello(String name) {
        // System.out.println("async provider received: " + name);
        // return "annotation: hello, " + name;
        throw new RuntimeException("Exception to show hystrix enabled.");
    }
}

配置Consumer端

對於Consumer端,則可以增加一層method呼叫,並在method上配置@HystrixCommand。當調用出錯時,會走到fallbackMethod = "reliable"的呼叫裡。

@Reference(version = "1.0.0")
    private HelloService demoService;

    @HystrixCommand(fallbackMethod = "reliable")
    public String doSayHello(String name) {
        return demoService.sayHello(name);
    }
    public String reliable(String name) {
        return "hystrix fallback value";
    }

測試:

1 按照上述方法服務提供者和消費者的pom中確保加入hystrix依賴包:

2 在服務提供者的Application入口類加上註解@EnableHystrix

3 在需要容錯的服務方法上加上註解@HystrixCommand

@Override
	public List<User> getALlUsers(){
		System.out.println("getALlUsers in...");
//		try {
//			Thread.sleep(3000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		if(Math.random() > 0.5) {
			throw new RuntimeException("查詢所有使用者介面呼叫失敗!");
		}
		List<User> users = userMapper.getAllUsers();
		return users;
	}

我們讓當隨機數大於0.5就丟擲異常!

啟動服務提供者!

4 在服務消費者Application入口類上也加上註解@EnableHystrix

5 在服務消費者的呼叫方法上加上註解@HystrixCommand(fallbackMethod = "hello")

然後定義hello方法,當失敗的時候就會進入此方法進行容錯處理!


@Controller
public class UserController {


	private final static Logger logger = LogManager.getLogger(UserController.class);
	//自動注入遠端服務
	@Reference(loadbalance="random",timeout=1000)
	private UserService<User> userService;

	@HystrixCommand(fallbackMethod = "hello")
	@RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
	public @ResponseBody Object getAllUsers() throws Exception {
		logger.debug("test in............");
		JsonDTo jsonDto = new JsonDTo();
		List<User> users = userService.getALlUsers();
		jsonDto.setData(users);
		return jsonDto;
	}
	/**
	 * getAllUsers出錯時會進入此方法
	 * @return
	 * @throws Exception
	 */
	public @ResponseBody Object hello() throws Exception {
		logger.debug("test in............");
		JsonDTo jsonDto = new JsonDTo();
		List<User> users = new ArrayList<>();
		User user = new User();
		user.setName("jeffSheng");
		user.setAge(28);
		user.setRemark("碼農");
		user.setSex(1);
		users.add(user);
		jsonDto.setData(users);
		return jsonDto;
	}
	
	

}

啟動消費者!