spring-cloud服务请求线程隔离之hystrix

1、创建一个maven项目 hystrix-ribbon-threadpool-consumer

pom.xml


	junit
	junit
	3.8.1
	test


	org.springframework.boot
	spring-boot-starter-web


	org.springframework.cloud
	spring-cloud-starter-netflix-eureka-client
	2.1.0.RELEASE


	org.springframework.cloud
	spring-cloud-starter-netflix-hystrix
	2.1.0.RELEASE

application.yml

spring:
  application:
    name: hystrix-ribbon-threadpool-consumer

server: 
  port: 8082
  
eureka:
  client:
    serviceUrl: 
      defaultZone: http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
  instance:
    prefer-ip-address: true  #默认是hostname注册,改成IP注册

2、Service服务线程隔离配置

@Service
public class StudentService {

	@Autowired
	private LoadBalancerClient loadBalancerClient;

	/**
	 * 配置当并发高的时候服务降级,并返回拖底数据,防止服务雪崩
	 * @return
	 */
	@HystrixCommand(fallbackMethod="fallback", groupKey="eureka-provider", commandKey="studentList", threadPoolKey="eureka-provider",
			threadPoolProperties = {
					//线程池大小
					@HystrixProperty(name = "coreSize", value = "30"),
					//最大队列长度
					@HystrixProperty(name = "maxQueueSize", value = "100"),
					//线程存活时间
					@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
					//拒绝请求
					@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15")
			})
	public List studentList() {
		// 获取服务端
		ServiceInstance si = loadBalancerClient.choose("eureka-provider");//EUREKA-PROVIDER

		// 拼装服务端地址
		StringBuffer pUrl = new StringBuffer();
		pUrl.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/list");

		ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() {};

		//远程调用获取提供者的数据
		RestTemplate rt = new RestTemplate();
		ResponseEntity> resp = rt.exchange(pUrl.toString(), HttpMethod.GET, null, typeRef);
		List studentList = resp.getBody();
		return studentList;
	}
	
	/**
	 * fallback返回拖底数据
	 * 以下四种情况将触发getFallback调用
	 * 1、方法抛出非HystrixBadRequestException异常。
	 * 2、方法调用超时
	 * 3、熔断器开启拦截调用
	 * 4、线程池/队列/信号量是否跑满
	 * @return
	 */
	public  List fallback(){
		List list = new ArrayList();
		list.add(new Student("fallback",-1));
		return list;
	}
}

3、测试类

@RestController
public class StudentController {
	
	@Autowired
	private StudentService studentService;
	
	@GetMapping("list")
	public List list(){
		return studentService.studentList();
	}
}

 

你可能感兴趣的:(spring)