文章目录

一、自定义限流处理

​自定义限流文档​

1. 自定义处理类
package com.gblfy.distributedlimiter.handle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.gblfy.distributedlimiter.enums.ServiceErrCode;
import com.gblfy.distributedlimiter.exception.BaseServiceException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Springboot自定义全局异常类返回json

*/
@Component
public class LimiterBlockHandler implements BlockExceptionHandler {

@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
//如果超过流控管理的就抛出异常
throw new BaseServiceException(ServiceErrCode.REQ_PARAM_ERR.getMsg(), ServiceErrCode.REQ_PARAM_ERR);
}
}
2. 请求一次测试

由于sentinel流控规则存在内存中,springboot项目重启,流控规则就没了,需要重新设置,下面会重点解决此问题

http://localhost:8082/sentinel
3. 重新配置流控规则

Springboot/Cloud集成Sentinel进阶实战_Sentinel

4. 重新测试
http://localhost:8082/sentinel

请求数量>1

Springboot/Cloud集成Sentinel进阶实战_spring_02

5. controller
package com.gblfy.distributedlimiter.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelLimiterController {

@GetMapping("/sentinel")
public String sentinel() {
return "sentinel";
}
}

Springboot全局异常统一处理返回json

二、方法限流处理
2.1. 创建接口
package com.gblfy.distributedlimiter.service;

public interface LimiterService {

public String process();
}
2.2. 创建接口实现类
package com.gblfy.distributedlimiter.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.gblfy.distributedlimiter.service.LimiterService;
import org.springframework.stereotype.Service;

@Service
public class LimiterServiceImpl implements LimiterService {

@Override
@SentinelResource("LimiterService.process")//自定义埋点
public String process() {
return "process";
}
}
2.3. 接口调用
package com.gblfy.distributedlimiter.controller;

import com.gblfy.distributedlimiter.service.LimiterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelLimiterController {

@Autowired
private LimiterService limiterService;

@GetMapping("/sentinel")
public String sentinel() {
return limiterService.process();
}
}
2.4. 请求

​http://localhost:8082/sentinel​

2.5. 设置流控规则

Springboot/Cloud集成Sentinel进阶实战_限流_03