利用SpringCloud搭建微服务3——服务容错组件Hystrix与负载均衡组件Ribbon的结合使用

配置文件application.properties

eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
server.port=9005
spring.application.name=service-ribbon-hystrix

启动类代码如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class RHystrixClientStarter {
	@Bean
	@LoadBalanced
	public RestTemplate getResource(){
		return new RestTemplate();
	}
	
	public static void main(String[] args) {
		SpringApplication.run(RHystrixClientStarter.class, args);
	}
}

控制层示例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
public class HiController {
	
	@Autowired
	private RestTemplate template;
	@RequestMapping("hi")
	@ResponseBody
	public String hello(String name){
		//利用template对象访问服务
		//url是服务连接地址
		//http://service-hi对应了后台服务提供者的工程
		///hi?name=传入的参数
		//相当于用服务名称代替了工程访问的域名+端口
		String hi = template.getForObject(
		"http://service-hi/hi?name="+name, String.class);
		return hi;
	}
}

pom.xml核心配置:

 
		org.springframework.boot
		spring-boot-starter-parent
		1.5.9.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
		Edgware.RELEASE
	
      
		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
		
			org.springframework.cloud
			spring-cloud-starter-eureka
		

		
		
			org.springframework.cloud
			spring-cloud-starter-ribbon
		
  
  
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				${spring-cloud.version}
				pom
				import
			
		
	

你可能感兴趣的:(微服务,Hystrix)