您的位置:首页 > 编程语言 > Java开发

spring cloud学习笔记2(负载均衡ribbon,服务容错保护Hystrix)

2018-01-24 17:26 686 查看
1.服务提供者只需要启动多个服务实例并注册到一个注册中心或者时多个相关联的服务注册中心

2.服务消费者直接通过调用被@LoadBanced注册修饰过的RestTemplate来实现面向服务的接口调用

在eureka-consumer中已经通过调用实现了负载均衡

package com.study.cloud.consumer.configs;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class WebConfig {

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

3.服务容错保护hystrix

向eureka-consumer中pom中pom中添加依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>修改启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class EurekaConsumerApplication {

public static void main(String[] args) {
SpringApplication.run(EurekaConsumerApplication.class, args);
}
}


增加service
package com.study.cloud.consumer.services;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;

@HystrixCommand(fallbackMethod = "helloFallBack")
public String helloConsumer() {
return restTemplate.getForEntity("http://HI-SERVICE/hello?name=youlangta", String.class).getBody();
}

public String helloFallBack() {
return "error";
}
}

改动conroller
package com.study.cloud.consumer.controllers;

import com.study.cloud.consumer.services.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

@Autowired
HelloService helloService;

@RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
public String helloConsumer() {
return helloService.helloConsumer();
}

}把所有项目启动,调用http://localhost:9000/



目前有两个服务,则调用http://localhost:9002/ribbon-consumer,

HI-SERVICE,host:localhost,port:9003 say hello youlangta
HI-SERVICE,host:localhost,port:9001 say hello youlangta
轮流出现

现在我们关闭9001,在次调用http://localhost:9002/ribbon-consumer多次,则会出现



表示容错机制成功
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sring cloud 微服务 RPC