《spring cloud微服务实战》读书笔记——Spring Cloud Hystrix(四)使用详解(一)

来源:互联网 发布:套定额软件 编辑:程序博客网 时间:2024/05/16 17:02

在前面的快速入门中我们已经简单的使用到了spring cloud hystrix,现在就来详细的说一下spring cloud hystrix 的用法。

1、通过继承的方式来创建一个命令

首先在服务的提供方eureka-service项目中创建一个新的接口,该接口只返回字符串”haha”
这里写图片描述

@RestControllerpublic class CommandController {    @RequestMapping(value="command-service",method = RequestMethod.GET)    @ResponseBody    public String index(){        return  "haha";    }}

接下来回到服务的调用方ribbon-consumer项目中,在这里我们通过继承的方式创建一个命令MyHystrixCommand 类,并重写HystrixCommand类的run方法,在重写的run方法中封装了具体的依赖服务调用逻辑。

这里写图片描述

public class MyHystrixCommand extends HystrixCommand<String> {    private RestTemplate restTemplate;    public MyHystrixCommand(Setter setter,RestTemplate restTemplate){        super(setter);        this.restTemplate = restTemplate;    }    @Override    protected String run() throws Exception {        return restTemplate.getForEntity("http://eureka-service/command-service", String.class).getBody();    }}

命令类已经创建完成,接下来要做的就是创建命令实例,并通过命令来调用相关服务。
接下来创建一个新的controller这里写图片描述

完整的代码如下

@RestControllerpublic class CommandController {    @Autowired    ConsumerService consumerService;    @Resource    RestTemplate restTemplate;    @RequestMapping(value="/helloCommand",method = RequestMethod.GET)    @ResponseBody    public String helloCommand(){        HystrixCommand.Setter setter = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("helloHystrixCommand"));        MyHystrixCommand myHystrixCommand = new MyHystrixCommand(setter, restTemplate);        String result = myHystrixCommand.execute();        return result;    }}

分析:
1、从上面MyHystrixCommand类的构造函数中可以发现,MyHystrixCommand类的构造器中有一个形参Setter setter,这个Setter其实是我们继承的HystrixCommand类中的一个静态类。这个静态类可以实现命令命名,命令分组以及线程池的划分等一系列操作。所以上面代码的意思是给当前创建的命令取名”helloHystrixCommand”,这是固定操作。
2、创建完命令后通过该命令调用了一个execute()方法,用于同步的执行命令。
也可以使用异步的方式,通过调用命令的queue()方法就可以实现,代码如下。

 Future<String> queue = myHystrixCommand.queue();        String result = queue.get();

两种方式都可以成功的返回字符串haha
这里写图片描述

阅读全文
0 0