Springboot/Cloud集成Sentinel进阶实战
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
一、自定义限流处理
自定义限流文档
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
* https://www.cnblogs.com/maolinjava/archive/2018/12/28/10193280.html
*/
@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);
}
}
//这里采用了返回json
2. 请求一次测试
由于sentinel流控规则存在内存中,springboot项目重启,流控规则就没了,需要重新设置,下面会重点解决此问题
http://localhost:8082/sentinel
3. 重新配置流控规则
4. 重新测试
http://localhost:8082/sentinel
请求数量>1
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
https://gblfy.blog.csdn.net/article/details/113824175
二、方法限流处理
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. 设置流控规则
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/weixin_40816738/article/details/113823742
锋哥最新SpringCloud分布式电商秒杀课程发布
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈
评论