第一步:pom.xml引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
第二步:再每个服务模块开启请求日志等信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.yml进行配置
management:
endpoints:
web:
exposure:
include: '*'
第三步:下载sentinel可视化界面
sentinel-dashboard-1.8.1
启动:java -jar sentinel-dashboard-1.8.1
第四步:配置QPS流控自定义返回信息
package com.atguigu.gulimall.coupon.config;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.common.utils.R;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author lichi
* @create 2021-08-12 9:34
*/
@Configuration
public class CouponSentinelConfig {
public CouponSentinelConfig() {
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
R error = R.error(1000,"当前流量较大,请稍后访问!");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().write(JSON.toJSONString(error));
}
});
}
}
运行结果
{“msg”:“当前流量较大,请稍后访问!”,“code”:1000}