正常的feign调用
@FeignClient(value = "gulimall-seckill",fallback = SeckillFeignServiceFallback.class)
public interface SeckillFeignService {
/**
* 写给商品服务的接口,查询秒杀服务信息
* @param skuId
* @return
*/
@GetMapping("/currentSeckillSkus/sku/seckill/{skuId}")
R getSkuSeckillInfo(@PathVariable("skuId") Long skuId);
}
兜底方法返回另外的信息
/**
* 如果feign调用失败返回的信息
*/
@Component
public class SeckillFeignServiceFallback implements SeckillFeignService {
@Override
public R getSkuSeckillInfo(Long skuId) {
return R.error(500,方法调用失败);
}
}
@Override
public List getCurrentSeckillSkus() {
//1.确定当前时间属于哪个秒杀场次
long time = new Date().getTime();
try(Entry seckillSkus = SphU.entry("seckillSkus")){
//正常的业务代码-----
}
//然后在可视化工具中对这个代码进行限流控制设置
}catch (BlockException e){
System.out.println("资源被限流");
}
return null;
}
**
* 自定义流量控制请求失败后返回信息
*/
@Configuration
public class SeckillSentinelConfig {
public SeckillSentinelConfig(){
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMsg());
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().write(JSON.toJSONString(error));
}
});
}
}
public List blockHandler(BlockException e){
log.error("getCurrentSeckillSkus被限流了");
return null;
}
/**
* 返回当前时间段可以参加秒杀的商品信息
* Entry seckillSkus = SphU.entry("seckillSkus"对代码进行降级
* @return
*/
@SentinelResource(value = "getCurrentSeckillSkus",blockHandler = "blockHandler")
@Override
public List getCurrentSeckillSkus() {
return null;
}
@SentinelResource(value = "getCurrentSeckillSkus",blockHandler = "blockHandler")
value的名称是可视化页面的限流处理名称
blockHandler的内容是限流降级后的操作方法
两个方法返回类型要一致
引入依赖
com.alibaba.cloud
spring-cloud-alibaba-sentinel-gateway
2.1.0.RELEASE
版本需要和common中的阿里依赖一致
com.alibaba.cloud
spring-cloud-alibaba-dependencies
2.1.0.RELEASE
pom
import
config文件
@Configuration
public class SentinelGatewayConfig {
public SentinelGatewayConfig(){
GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
@Override
public Mono handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMsg());
String jsonString = JSON.toJSONString(error);
Mono body = ServerResponse.ok().body(Mono.just(jsonString), String.class);
return body;
}
});
}
}
也可以配置相关的信息
配置网关返回的状态码
spring.cloud.sentinel.scg.fallback.response-status=400