•信号量的限流策略方式:使用java.util.concurrent.semophore
1.生产者端:
package com.cc.springcloud.api;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cc.springcloud.entity.User;
@RestController
public class ProviderController {
//信号量限流的方法
@RequestMapping(value="/semaphore")
public String semaphore() throws Exception {
System.out.println("provider-1:------> semaphore");
//模拟访问耗时
Thread.sleep(RandomUtils.nextInt(1500, 2500));
return "provider-1";
}
}
2.消费者端:
package com.cc.springcloud.service;
import java.util.List;
import java.util.concurrent.Future;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.cc.springcloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
/**
* Hystrix实现限流机制:使用Semaphore方式:使用java.util.concurrent.semophore
*
*/
@HystrixCommand(
commandKey = "semaphoreKey1",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy",value="SEMAPHORE"),
//某一时间最大允许并发请求个数
@HystrixProperty(name="execution.isolation.semaphore.maxConcurrentRequests",value="10")
},
fallbackMethod = "semaphoreFailback"
)
public String semaphore() {
String ret = restTemplate.getForObject("http://provider-service/semaphore", String.class);
System.out.println("输出调用结果:"+ret);
return ret;
}
public String semaphoreFailback() {
System.out.println("-------semaphore限流,降级策略!-----------------");
return "-------semaphore限流,降级策略!-----------------";
}
}
--------------------------------------------------------------------------------------------
package com.cc.springcloud.api;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cc.springcloud.entity.User;
import com.cc.springcloud.service.HelloService;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
@RestController
public class ConsumerController {
@Autowired
private HelloService helloService;
//访问semaphroe限流接口
@RequestMapping(value="/hystrix-semaphore")
public String semaphore() throws Exception {
return helloService.semaphore();
}
}
3.启动集群测试:JMeter模拟测试
结果输出: