通过继承 HystrixCommand 的方式无法实现服务降级

问题:

写了个DEMO 通过 继承 HystrixCommand 的方式无法实现服务降级。

原因:

在 main 方法中直接调用 run 方法。

有问题的代码:

public static void main(String[] args) throws Exception {
		System.out.println(userCommand);
		userCommand.run();
	}

修复问题的代码:

public static void main(String[] args) throws Exception {
		String userCommand = new UserCommand().execute();
		System.out.println(userCommand);
		//userCommand.run();
		
		Future<String> fWorld = new UserCommand().queue();
                System.out.println("测试异步执行"+fWorld.get());  //一步执行用get()来获取结果
	}

完整的有问题的代码:

package com.example.server1;

import java.util.concurrent.Future;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

public class UserCommand extends HystrixCommand<String> {
	public UserCommand() {
		super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
	}
	
	@Override
	protected String run() throws Exception {
		//return restTemplate.getForObject("http://hello-service/users/{1}", User.class,id);
		int i=1/0;
		return "成功";
	}
	
	
	@Override
	protected String getFallback() {
		return "faild";
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(userCommand);
		userCommand.run();
		
	}
	
}

完整的修复问题后的代码:

package com.example.server1;

import java.util.concurrent.Future;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

public class UserCommand extends HystrixCommand<String> {
	public UserCommand() {
		super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
	}
	
	@Override
	protected String run() throws Exception {
		//return restTemplate.getForObject("http://hello-service/users/{1}", User.class,id);
		int i=1/0;
		return "成功";
	}
	
	
	@Override
	protected String getFallback() {
		return "faild";
	}
	
	public static void main(String[] args) throws Exception {
		String userCommand = new UserCommand().execute();
		System.out.println(userCommand);
		//userCommand.run();
		
		Future<String> fWorld = new UserCommand().queue();
        System.out.println("测试异步执行"+fWorld.get());  //一步执行用get()来获取结果
	}
	
}

猜你喜欢

转载自blog.csdn.net/lixiaxin200319/article/details/81069707
今日推荐