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

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中添加依赖

 
            org.springframework.cloud
            spring-cloud-starter-hystrix
        
修改启动类

@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/

spring cloud学习笔记2(负载均衡ribbon,服务容错保护Hystrix)_第1张图片

目前有两个服务,则调用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多次,则会出现

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

表示容错机制成功


你可能感兴趣的:(java,sring,cloud,微服务,RPC)