千家信息网

11、RestTemplate+Ribbon整合断路器Hys

发表于:2024-10-09 作者:千家信息网编辑
千家信息网最后更新 2024年10月09日,在微服务架构中,根据业务需求拆分成一个个的微小服务,然后服务与服务之间可以相互RPC远程调用。在Spring Cloud可以使用RestTemplate+Ribbon或者Feign来进行RPC远程调用
千家信息网最后更新 2024年10月09日11、RestTemplate+Ribbon整合断路器Hys

在微服务架构中,根据业务需求拆分成一个个的微小服务,然后服务与服务之间可以相互RPC远程调用。在Spring Cloud可以使用RestTemplate+Ribbon或者Feign来进行RPC远程调用。为了保证服务高可用性,单个服务通常会进行集群部署。由于网络原因或者自身的原因,服务并不能保证百分之一百可用,如果服务方出现问题,调用这个服务就会出现线程阻塞,此时若有出现大量请求,导致服务方瘫痪。这时断路器就派上用场了。

当对某个服务的调用的不可用达到一个阀值(Hystric 默认是5秒20次) 断路器将会被自动被打开。断路打开后, fallback方法可以直接返回一个预先设置的固定值。

1、 新建项目sc-eureka-client-consumer-ribbon-hystrix,对应的pom.xml文件

    4.0.0    spring-cloud    sc-eureka-client-consumer-ribbon    0.0.1-SNAPSHOT    jar    sc-eureka-client-consumer-ribbon    http://maven.apache.org            org.springframework.boot        spring-boot-starter-parent        2.0.4.RELEASE                                            org.springframework.cloud                spring-cloud-dependencies                Finchley.RELEASE                pom                import                                    UTF-8        1.8        1.8                            org.springframework.cloud            spring-cloud-starter-netflix-eureka-client                                    org.springframework.cloud            spring-cloud-starter-netflix-ribbon                                org.springframework.boot                spring-boot-starter-web                                        org.springframework.cloud                spring-cloud-starter-netflix-hystrix                2.0.1.RELEASE            

备注:spring-cloud-starter-hystrix已经在spring cloud 2.x标注成过期。推荐使用spring-cloud-starter-netflix-hystrix

2、 新建spring boot 启动类ConsumerApplication.java

package sc.consumer;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.cloud.netflix.hystrix.EnableHystrix;@SpringBootApplication@EnableEurekaClient@EnableHystrixpublic class ConsumerHystrixApplication {    public static void main(String[] args) {        SpringApplication.run(ConsumerHystrixApplication.class, args);    }}

可以看出这个启动类只是《服务发现&服务消费者Ribbon》的启动类添加多了一个注解EnableHystrix(启动断路器)

3、 编写服务类,并添加断路器注解

package sc.consumer.service.impl;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;import com.github.andrewoma.dexx.collection.ArrayList;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import sc.consumer.model.User;import sc.consumer.service.UserService;@Servicepublic class UserServiceImpl implements UserService{    @Autowired    private RestTemplate restTemplate;    @HystrixCommand(fallbackMethod = "getUserError")    @Override    public Map getUser(Long id) {        return restTemplate.getForObject("http://sc-eureka-client-provider:8200/user/getUser/{1}", Map.class, id);    }    public Map getUserError(Long id){        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        User u = new User();        u.setId(-1L);        u.setUserName("failName");        map.put("body", u);        return map;    }    @HystrixCommand(fallbackMethod = "listUserError")    @Override    public Map listUser() {        return restTemplate.getForObject("http://sc-eureka-client-provider:8200/user/listUser", Map.class);    }    public Map listUserError(){        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        map.put("body", new ArrayList());        return map;    }    @HystrixCommand(fallbackMethod = "addUserError")    @Override    public Map addUser(User user) {        return restTemplate.postForObject("http://sc-eureka-client-provider:8200/user/addUser", user, Map.class);    }    public Map addUserError(User user){        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        map.put("body", 0);        return map;    }    @HystrixCommand(fallbackMethod = "updateUserError")    @Override    public Map updateUser(User user) {        restTemplate.put("http://sc-eureka-client-provider:8200/user/updateUser",user);        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        return map;    }    public Map updateUserError(User user){        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        map.put("body", 0);        return map;    }    @HystrixCommand(fallbackMethod = "deleteUserError")    @Override    public Map deleteUser(Long id) {        restTemplate.delete("http://sc-eureka-client-provider:8200/user/deleteUser/{id}", id);        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        return map;    }    public Map deleteUserError(Long id){        Map map = new HashMap();        map.put("code", "000000");        map.put("msg", "ok");        map.put("body", 0);        return map;    }}

添加HystrixCommand注解,对应的参数fallbackMethod值为当方式服务方无法调用时,返回预设值得方法名。

4、 新建配置文件bootstrap.yml和application.yml
bootstrap.yml

server:    port: 5600application.ymlspring:    application:        name: sc-eureka-client-consumer-ribbon-hystrixeureka:    instance:        hostname: 127.0.0.1    client:        #由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己        registerWithEureka: true        #由于注册中心的职责就是维护服务实例,它并不需要去检索服务,所以也设置为false        fetchRegistry: true        serviceUrl:            defaultZone: http://127.0.0.1:5001/eureka/

5、 其他项目文件参加下图

6、 分别启动注册中心sc-eureka-server和服务提供者sc-eureka-client-provider

7、 启动sc-eureka-client-consumer-ribbon-hystrix,并验证是否启动成功
方式一:查看日志

方式二:查看注册中心是否注册成功


8、 验证断路器是否起作用
(1) 服务提供者正常时访问:
http://127.0.0.1:5600/cli/user/getUser/4

正常返回数据库里的数据
(2) 服务提供者关闭时访问:
http://127.0.0.1:5600/cli/user/getUser/4

对比两个返回的数据,可以看出服务提供者关闭时,返回的数据是在程序写死的数据,如下图:

其他方法可以自行按照以上方式进行验证。

公众号:java乐园

0