SpringCloud教程之服务消费者(rest + ribbon + hystrix)(五)

SpringCloud服务消费者rest + ribbon + hystrix

在父工程目录下创建一个maven项目,在这个maven项目中添加依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
    </dependencies>

在配置文件application.yml中添加以下配置

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:7010/eureka/
server:
  port: 8777
spring:
  application:
    name: ribbon-service

management:
  endpoints:
    web:
      exposure:
        include: hystrix.stream
  endpoint:
    health:
      show-details: always

启动类

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class RibbonApplication {
    public static void main(String[] args) {
        SpringApplication.run( RibbonApplication.class, args );
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Web层

@Controller
public class RemoteRibbon {

    @Autowired
    RemoteService remoteService;

    @GetMapping("/hi")
    public String hi(@RequestParam String name) {
        return remoteService.hiService(name);
    }
}

service层

@Service
public class RemoteService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        String forObject = restTemplate.getForObject("http://server02/hi?name=" + name, String.class);
        System.out.println(forObject);
        return forObject;
    }

    public String hiError(String name) {
        return "Hystrix:" + name;
    }
}

依次启动Eureka、config-server、再启动本服务

在浏览器上访问http://localhost:8777/hi?name=啊啊啊 ,返回服务提供者的值

关闭服务提供者服务,再次访问返回Hystrix: 啊啊啊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值